sio.c revision 89463
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 89463 2002-01-17 16:16:51Z imp $
34 *	from: @(#)com.c	7.5 (Berkeley) 5/16/91
35 *	from: i386/isa sio.c,v 1.234
36 */
37
38#include "opt_comconsole.h"
39#include "opt_compat.h"
40#include "opt_ddb.h"
41#include "opt_sio.h"
42
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		printf(
770		"sio%d: port may not be enabled in BIOS\n",
771		    device_get_unit(dev));
772	}
773	if (bootverbose)
774		printf("sio%d: irq maps: %#x %#x %#x %#x\n",
775		    device_get_unit(dev),
776		    irqmap[0], irqmap[1], irqmap[2], irqmap[3]);
777
778	result = 0;
779	for (fn = 0; fn < sizeof failures; ++fn)
780		if (failures[fn]) {
781			sio_setreg(com, com_mcr, 0);
782			result = ENXIO;
783			if (bootverbose) {
784				printf("sio%d: probe failed test(s):",
785				    device_get_unit(dev));
786				for (fn = 0; fn < sizeof failures; ++fn)
787					if (failures[fn])
788						printf(" %d", fn);
789				printf("\n");
790			}
791			break;
792		}
793	bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
794	if (iobase == siocniobase)
795		result = 0;
796	if (result != 0) {
797		device_set_softc(dev, NULL);
798		free(com, M_DEVBUF);
799	}
800	return (result);
801}
802
803#ifdef COM_ESP
804static int
805espattach(com, esp_port)
806	struct com_s		*com;
807	Port_t			esp_port;
808{
809	u_char	dips;
810	u_char	val;
811
812	/*
813	 * Check the ESP-specific I/O port to see if we're an ESP
814	 * card.  If not, return failure immediately.
815	 */
816	if ((inb(esp_port) & 0xf3) == 0) {
817		printf(" port 0x%x is not an ESP board?\n", esp_port);
818		return (0);
819	}
820
821	/*
822	 * We've got something that claims to be a Hayes ESP card.
823	 * Let's hope so.
824	 */
825
826	/* Get the dip-switch configuration */
827	outb(esp_port + ESP_CMD1, ESP_GETDIPS);
828	dips = inb(esp_port + ESP_STATUS1);
829
830	/*
831	 * Bits 0,1 of dips say which COM port we are.
832	 */
833	if (rman_get_start(com->ioportres) == likely_com_ports[dips & 0x03])
834		printf(" : ESP");
835	else {
836		printf(" esp_port has com %d\n", dips & 0x03);
837		return (0);
838	}
839
840	/*
841	 * Check for ESP version 2.0 or later:  bits 4,5,6 = 010.
842	 */
843	outb(esp_port + ESP_CMD1, ESP_GETTEST);
844	val = inb(esp_port + ESP_STATUS1);	/* clear reg 1 */
845	val = inb(esp_port + ESP_STATUS2);
846	if ((val & 0x70) < 0x20) {
847		printf("-old (%o)", val & 0x70);
848		return (0);
849	}
850
851	/*
852	 * Check for ability to emulate 16550:  bit 7 == 1
853	 */
854	if ((dips & 0x80) == 0) {
855		printf(" slave");
856		return (0);
857	}
858
859	/*
860	 * Okay, we seem to be a Hayes ESP card.  Whee.
861	 */
862	com->esp = TRUE;
863	com->esp_port = esp_port;
864	return (1);
865}
866#endif /* COM_ESP */
867
868int
869sioattach(dev, xrid)
870	device_t	dev;
871	int		xrid;
872{
873	struct com_s	*com;
874#ifdef COM_ESP
875	Port_t		*espp;
876#endif
877	Port_t		iobase;
878	int		unit;
879	u_int		flags;
880	int		rid;
881	struct resource *port;
882	int		ret;
883
884	rid = xrid;
885	port = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid,
886				  0, ~0, IO_COMSIZE, RF_ACTIVE);
887	if (!port)
888		return (ENXIO);
889
890	iobase = rman_get_start(port);
891	unit = device_get_unit(dev);
892	com = device_get_softc(dev);
893	flags = device_get_flags(dev);
894
895	if (unit >= sio_numunits)
896		sio_numunits = unit + 1;
897	/*
898	 * sioprobe() has initialized the device registers as follows:
899	 *	o cfcr = CFCR_8BITS.
900	 *	  It is most important that CFCR_DLAB is off, so that the
901	 *	  data port is not hidden when we enable interrupts.
902	 *	o ier = 0.
903	 *	  Interrupts are only enabled when the line is open.
904	 *	o mcr = MCR_IENABLE, or 0 if the port has AST/4 compatible
905	 *	  interrupt control register or the config specifies no irq.
906	 *	  Keeping MCR_DTR and MCR_RTS off might stop the external
907	 *	  device from sending before we are ready.
908	 */
909	bzero(com, sizeof *com);
910	com->unit = unit;
911	com->ioportres = port;
912	com->bst = rman_get_bustag(port);
913	com->bsh = rman_get_bushandle(port);
914	com->cfcr_image = CFCR_8BITS;
915	com->dtr_wait = 3 * hz;
916	com->loses_outints = COM_LOSESOUTINTS(flags) != 0;
917	com->no_irq = bus_get_resource(dev, SYS_RES_IRQ, 0, NULL, NULL) != 0;
918	com->tx_fifo_size = 1;
919	com->obufs[0].l_head = com->obuf1;
920	com->obufs[1].l_head = com->obuf2;
921
922	com->data_port = iobase + com_data;
923	com->int_id_port = iobase + com_iir;
924	com->modem_ctl_port = iobase + com_mcr;
925	com->mcr_image = inb(com->modem_ctl_port);
926	com->line_status_port = iobase + com_lsr;
927	com->modem_status_port = iobase + com_msr;
928	com->intr_ctl_port = iobase + com_ier;
929
930	/*
931	 * We don't use all the flags from <sys/ttydefaults.h> since they
932	 * are only relevant for logins.  It's important to have echo off
933	 * initially so that the line doesn't start blathering before the
934	 * echo flag can be turned off.
935	 */
936	com->it_in.c_iflag = 0;
937	com->it_in.c_oflag = 0;
938	com->it_in.c_cflag = TTYDEF_CFLAG;
939	com->it_in.c_lflag = 0;
940	if (unit == comconsole) {
941		com->it_in.c_iflag = TTYDEF_IFLAG;
942		com->it_in.c_oflag = TTYDEF_OFLAG;
943		com->it_in.c_cflag = TTYDEF_CFLAG | CLOCAL;
944		com->it_in.c_lflag = TTYDEF_LFLAG;
945		com->lt_out.c_cflag = com->lt_in.c_cflag = CLOCAL;
946		com->lt_out.c_ispeed = com->lt_out.c_ospeed =
947		com->lt_in.c_ispeed = com->lt_in.c_ospeed =
948		com->it_in.c_ispeed = com->it_in.c_ospeed = comdefaultrate;
949	} else
950		com->it_in.c_ispeed = com->it_in.c_ospeed = TTYDEF_SPEED;
951	if (siosetwater(com, com->it_in.c_ispeed) != 0) {
952		mtx_unlock_spin(&sio_lock);
953		/*
954		 * Leave i/o resources allocated if this is a `cn'-level
955		 * console, so that other devices can't snarf them.
956		 */
957		if (iobase != siocniobase)
958			bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
959		return (ENOMEM);
960	}
961	mtx_unlock_spin(&sio_lock);
962	termioschars(&com->it_in);
963	com->it_out = com->it_in;
964
965	/* attempt to determine UART type */
966	printf("sio%d: type", unit);
967
968
969#ifdef COM_MULTIPORT
970	if (!COM_ISMULTIPORT(flags) && !COM_IIR_TXRDYBUG(flags))
971#else
972	if (!COM_IIR_TXRDYBUG(flags))
973#endif
974	{
975		u_char	scr;
976		u_char	scr1;
977		u_char	scr2;
978
979		scr = sio_getreg(com, com_scr);
980		sio_setreg(com, com_scr, 0xa5);
981		scr1 = sio_getreg(com, com_scr);
982		sio_setreg(com, com_scr, 0x5a);
983		scr2 = sio_getreg(com, com_scr);
984		sio_setreg(com, com_scr, scr);
985		if (scr1 != 0xa5 || scr2 != 0x5a) {
986			printf(" 8250 or not responding");
987			goto determined_type;
988		}
989	}
990	sio_setreg(com, com_fifo, FIFO_ENABLE | FIFO_RX_HIGH);
991	DELAY(100);
992	com->st16650a = 0;
993	switch (inb(com->int_id_port) & IIR_FIFO_MASK) {
994	case FIFO_RX_LOW:
995		printf(" 16450");
996		break;
997	case FIFO_RX_MEDL:
998		printf(" 16450?");
999		break;
1000	case FIFO_RX_MEDH:
1001		printf(" 16550?");
1002		break;
1003	case FIFO_RX_HIGH:
1004		if (COM_NOFIFO(flags)) {
1005			printf(" 16550A fifo disabled");
1006		} else {
1007			com->hasfifo = TRUE;
1008			if (COM_ST16650A(flags)) {
1009				com->st16650a = 1;
1010				com->tx_fifo_size = 32;
1011				printf(" ST16650A");
1012			} else {
1013				com->tx_fifo_size = COM_FIFOSIZE(flags);
1014				printf(" 16550A");
1015			}
1016		}
1017#ifdef COM_ESP
1018		for (espp = likely_esp_ports; *espp != 0; espp++)
1019			if (espattach(com, *espp)) {
1020				com->tx_fifo_size = 1024;
1021				break;
1022			}
1023#endif
1024		if (!com->st16650a) {
1025			if (!com->tx_fifo_size)
1026				com->tx_fifo_size = 16;
1027			else
1028				printf(" lookalike with %d bytes FIFO",
1029				    com->tx_fifo_size);
1030		}
1031
1032		break;
1033	}
1034
1035#ifdef COM_ESP
1036	if (com->esp) {
1037		/*
1038		 * Set 16550 compatibility mode.
1039		 * We don't use the ESP_MODE_SCALE bit to increase the
1040		 * fifo trigger levels because we can't handle large
1041		 * bursts of input.
1042		 * XXX flow control should be set in comparam(), not here.
1043		 */
1044		outb(com->esp_port + ESP_CMD1, ESP_SETMODE);
1045		outb(com->esp_port + ESP_CMD2, ESP_MODE_RTS | ESP_MODE_FIFO);
1046
1047		/* Set RTS/CTS flow control. */
1048		outb(com->esp_port + ESP_CMD1, ESP_SETFLOWTYPE);
1049		outb(com->esp_port + ESP_CMD2, ESP_FLOW_RTS);
1050		outb(com->esp_port + ESP_CMD2, ESP_FLOW_CTS);
1051
1052		/* Set flow-control levels. */
1053		outb(com->esp_port + ESP_CMD1, ESP_SETRXFLOW);
1054		outb(com->esp_port + ESP_CMD2, HIBYTE(768));
1055		outb(com->esp_port + ESP_CMD2, LOBYTE(768));
1056		outb(com->esp_port + ESP_CMD2, HIBYTE(512));
1057		outb(com->esp_port + ESP_CMD2, LOBYTE(512));
1058	}
1059#endif /* COM_ESP */
1060	sio_setreg(com, com_fifo, 0);
1061determined_type: ;
1062
1063#ifdef COM_MULTIPORT
1064	if (COM_ISMULTIPORT(flags)) {
1065		device_t masterdev;
1066
1067		com->multiport = TRUE;
1068		printf(" (multiport");
1069		if (unit == COM_MPMASTER(flags))
1070			printf(" master");
1071		printf(")");
1072		masterdev = devclass_get_device(sio_devclass,
1073		    COM_MPMASTER(flags));
1074		com->no_irq = (masterdev == NULL || bus_get_resource(masterdev,
1075		    SYS_RES_IRQ, 0, NULL, NULL) != 0);
1076	 }
1077#endif /* COM_MULTIPORT */
1078	if (unit == comconsole)
1079		printf(", console");
1080	if (COM_IIR_TXRDYBUG(flags))
1081		printf(" with a bogus IIR_TXRDY register");
1082	printf("\n");
1083
1084	if (sio_fast_ih == NULL) {
1085		swi_add(&tty_ithd, "tty:sio", siopoll, NULL, SWI_TTY, 0,
1086		    &sio_fast_ih);
1087		swi_add(&clk_ithd, "tty:sio", siopoll, NULL, SWI_TTY, 0,
1088		    &sio_slow_ih);
1089	}
1090	com->devs[0] = make_dev(&sio_cdevsw, unit,
1091	    UID_ROOT, GID_WHEEL, 0600, "ttyd%r", unit);
1092	com->devs[1] = make_dev(&sio_cdevsw, unit | CONTROL_INIT_STATE,
1093	    UID_ROOT, GID_WHEEL, 0600, "ttyid%r", unit);
1094	com->devs[2] = make_dev(&sio_cdevsw, unit | CONTROL_LOCK_STATE,
1095	    UID_ROOT, GID_WHEEL, 0600, "ttyld%r", unit);
1096	com->devs[3] = make_dev(&sio_cdevsw, unit | CALLOUT_MASK,
1097	    UID_UUCP, GID_DIALER, 0660, "cuaa%r", unit);
1098	com->devs[4] = make_dev(&sio_cdevsw,
1099	    unit | CALLOUT_MASK | CONTROL_INIT_STATE,
1100	    UID_UUCP, GID_DIALER, 0660, "cuaia%r", unit);
1101	com->devs[5] = make_dev(&sio_cdevsw,
1102	    unit | CALLOUT_MASK | CONTROL_LOCK_STATE,
1103	    UID_UUCP, GID_DIALER, 0660, "cuala%r", unit);
1104	com->flags = flags;
1105	com->pps.ppscap = PPS_CAPTUREASSERT | PPS_CAPTURECLEAR;
1106	pps_init(&com->pps);
1107
1108	rid = 0;
1109	com->irqres = bus_alloc_resource(dev, SYS_RES_IRQ, &rid, 0ul, ~0ul, 1,
1110	    RF_ACTIVE);
1111	if (com->irqres) {
1112		ret = BUS_SETUP_INTR(device_get_parent(dev), dev, com->irqres,
1113				     INTR_TYPE_TTY | INTR_FAST,
1114				     siointr, com, &com->cookie);
1115		if (ret) {
1116			ret = BUS_SETUP_INTR(device_get_parent(dev), dev,
1117					     com->irqres, INTR_TYPE_TTY,
1118					     siointr, com, &com->cookie);
1119			if (ret == 0)
1120				device_printf(dev, "unable to activate interrupt in fast mode - using normal mode\n");
1121		}
1122		if (ret)
1123			device_printf(dev, "could not activate interrupt\n");
1124#if defined(DDB) && (defined(BREAK_TO_DEBUGGER) || \
1125    defined(ALT_BREAK_TO_DEBUGGER))
1126		/*
1127		 * Enable interrupts for early break-to-debugger support
1128		 * on the console.
1129		 */
1130		if (ret == 0 && unit == comconsole)
1131			outb(siocniobase + com_ier, IER_ERXRDY | IER_ERLS |
1132			    IER_EMSC);
1133#endif
1134	}
1135
1136	return (0);
1137}
1138
1139static int
1140sioopen(dev, flag, mode, td)
1141	dev_t		dev;
1142	int		flag;
1143	int		mode;
1144	struct thread	*td;
1145{
1146	struct com_s	*com;
1147	int		error;
1148	int		mynor;
1149	int		s;
1150	struct tty	*tp;
1151	int		unit;
1152
1153	mynor = minor(dev);
1154	unit = MINOR_TO_UNIT(mynor);
1155	com = com_addr(unit);
1156	if (com == NULL)
1157		return (ENXIO);
1158	if (com->gone)
1159		return (ENXIO);
1160	if (mynor & CONTROL_MASK)
1161		return (0);
1162	tp = dev->si_tty = com->tp = ttymalloc(com->tp);
1163	s = spltty();
1164	/*
1165	 * We jump to this label after all non-interrupted sleeps to pick
1166	 * up any changes of the device state.
1167	 */
1168open_top:
1169	while (com->state & CS_DTR_OFF) {
1170		error = tsleep(&com->dtr_wait, TTIPRI | PCATCH, "siodtr", 0);
1171		if (com_addr(unit) == NULL)
1172			return (ENXIO);
1173		if (error != 0 || com->gone)
1174			goto out;
1175	}
1176	if (tp->t_state & TS_ISOPEN) {
1177		/*
1178		 * The device is open, so everything has been initialized.
1179		 * Handle conflicts.
1180		 */
1181		if (mynor & CALLOUT_MASK) {
1182			if (!com->active_out) {
1183				error = EBUSY;
1184				goto out;
1185			}
1186		} else {
1187			if (com->active_out) {
1188				if (flag & O_NONBLOCK) {
1189					error = EBUSY;
1190					goto out;
1191				}
1192				error =	tsleep(&com->active_out,
1193					       TTIPRI | PCATCH, "siobi", 0);
1194				if (com_addr(unit) == NULL)
1195					return (ENXIO);
1196				if (error != 0 || com->gone)
1197					goto out;
1198				goto open_top;
1199			}
1200		}
1201		if (tp->t_state & TS_XCLUDE &&
1202		    suser_td(td)) {
1203			error = EBUSY;
1204			goto out;
1205		}
1206	} else {
1207		/*
1208		 * The device isn't open, so there are no conflicts.
1209		 * Initialize it.  Initialization is done twice in many
1210		 * cases: to preempt sleeping callin opens if we are
1211		 * callout, and to complete a callin open after DCD rises.
1212		 */
1213		tp->t_oproc = comstart;
1214		tp->t_param = comparam;
1215		tp->t_stop = comstop;
1216		tp->t_dev = dev;
1217		tp->t_termios = mynor & CALLOUT_MASK
1218				? com->it_out : com->it_in;
1219		(void)commctl(com, TIOCM_DTR | TIOCM_RTS, DMSET);
1220		com->poll = com->no_irq;
1221		com->poll_output = com->loses_outints;
1222		++com->wopeners;
1223		error = comparam(tp, &tp->t_termios);
1224		--com->wopeners;
1225		if (error != 0)
1226			goto out;
1227		/*
1228		 * XXX we should goto open_top if comparam() slept.
1229		 */
1230		if (com->hasfifo) {
1231			/*
1232			 * (Re)enable and drain fifos.
1233			 *
1234			 * Certain SMC chips cause problems if the fifos
1235			 * are enabled while input is ready.  Turn off the
1236			 * fifo if necessary to clear the input.  We test
1237			 * the input ready bit after enabling the fifos
1238			 * since we've already enabled them in comparam()
1239			 * and to handle races between enabling and fresh
1240			 * input.
1241			 */
1242			while (TRUE) {
1243				sio_setreg(com, com_fifo,
1244					   FIFO_RCV_RST | FIFO_XMT_RST
1245					   | com->fifo_image);
1246				/*
1247				 * XXX the delays are for superstitious
1248				 * historical reasons.  It must be less than
1249				 * the character time at the maximum
1250				 * supported speed (87 usec at 115200 bps
1251				 * 8N1).  Otherwise we might loop endlessly
1252				 * if data is streaming in.  We used to use
1253				 * delays of 100.  That usually worked
1254				 * because DELAY(100) used to usually delay
1255				 * for about 85 usec instead of 100.
1256				 */
1257				DELAY(50);
1258				if (!(inb(com->line_status_port) & LSR_RXRDY))
1259					break;
1260				sio_setreg(com, com_fifo, 0);
1261				DELAY(50);
1262				(void) inb(com->data_port);
1263			}
1264		}
1265
1266		mtx_lock_spin(&sio_lock);
1267		(void) inb(com->line_status_port);
1268		(void) inb(com->data_port);
1269		com->prev_modem_status = com->last_modem_status
1270		    = inb(com->modem_status_port);
1271		if (COM_IIR_TXRDYBUG(com->flags)) {
1272			outb(com->intr_ctl_port, IER_ERXRDY | IER_ERLS
1273						| IER_EMSC);
1274		} else {
1275			outb(com->intr_ctl_port, IER_ERXRDY | IER_ETXRDY
1276						| IER_ERLS | IER_EMSC);
1277		}
1278		mtx_unlock_spin(&sio_lock);
1279		/*
1280		 * Handle initial DCD.  Callout devices get a fake initial
1281		 * DCD (trapdoor DCD).  If we are callout, then any sleeping
1282		 * callin opens get woken up and resume sleeping on "siobi"
1283		 * instead of "siodcd".
1284		 */
1285		/*
1286		 * XXX `mynor & CALLOUT_MASK' should be
1287		 * `tp->t_cflag & (SOFT_CARRIER | TRAPDOOR_CARRIER) where
1288		 * TRAPDOOR_CARRIER is the default initial state for callout
1289		 * devices and SOFT_CARRIER is like CLOCAL except it hides
1290		 * the true carrier.
1291		 */
1292		if (com->prev_modem_status & MSR_DCD || mynor & CALLOUT_MASK)
1293			(*linesw[tp->t_line].l_modem)(tp, 1);
1294	}
1295	/*
1296	 * Wait for DCD if necessary.
1297	 */
1298	if (!(tp->t_state & TS_CARR_ON) && !(mynor & CALLOUT_MASK)
1299	    && !(tp->t_cflag & CLOCAL) && !(flag & O_NONBLOCK)) {
1300		++com->wopeners;
1301		error = tsleep(TSA_CARR_ON(tp), TTIPRI | PCATCH, "siodcd", 0);
1302		if (com_addr(unit) == NULL)
1303			return (ENXIO);
1304		--com->wopeners;
1305		if (error != 0 || com->gone)
1306			goto out;
1307		goto open_top;
1308	}
1309	error =	(*linesw[tp->t_line].l_open)(dev, tp);
1310	disc_optim(tp, &tp->t_termios, com);
1311	if (tp->t_state & TS_ISOPEN && mynor & CALLOUT_MASK)
1312		com->active_out = TRUE;
1313	siosettimeout();
1314out:
1315	splx(s);
1316	if (!(tp->t_state & TS_ISOPEN) && com->wopeners == 0)
1317		comhardclose(com);
1318	return (error);
1319}
1320
1321static int
1322sioclose(dev, flag, mode, td)
1323	dev_t		dev;
1324	int		flag;
1325	int		mode;
1326	struct thread	*td;
1327{
1328	struct com_s	*com;
1329	int		mynor;
1330	int		s;
1331	struct tty	*tp;
1332
1333	mynor = minor(dev);
1334	if (mynor & CONTROL_MASK)
1335		return (0);
1336	com = com_addr(MINOR_TO_UNIT(mynor));
1337	if (com == NULL)
1338		return (ENODEV);
1339	tp = com->tp;
1340	s = spltty();
1341	(*linesw[tp->t_line].l_close)(tp, flag);
1342	disc_optim(tp, &tp->t_termios, com);
1343	comstop(tp, FREAD | FWRITE);
1344	comhardclose(com);
1345	ttyclose(tp);
1346	siosettimeout();
1347	splx(s);
1348	if (com->gone) {
1349		printf("sio%d: gone\n", com->unit);
1350		s = spltty();
1351		if (com->ibuf != NULL)
1352			free(com->ibuf, M_DEVBUF);
1353		bzero(tp, sizeof *tp);
1354		splx(s);
1355	}
1356	return (0);
1357}
1358
1359static void
1360comhardclose(com)
1361	struct com_s	*com;
1362{
1363	int		s;
1364	struct tty	*tp;
1365	int		unit;
1366
1367	unit = com->unit;
1368	s = spltty();
1369	com->poll = FALSE;
1370	com->poll_output = FALSE;
1371	com->do_timestamp = FALSE;
1372	com->do_dcd_timestamp = FALSE;
1373	com->pps.ppsparam.mode = 0;
1374	sio_setreg(com, com_cfcr, com->cfcr_image &= ~CFCR_SBREAK);
1375	tp = com->tp;
1376
1377#if defined(DDB) && (defined(BREAK_TO_DEBUGGER) || \
1378    defined(ALT_BREAK_TO_DEBUGGER))
1379	/*
1380	 * Leave interrupts enabled and don't clear DTR if this is the
1381	 * console. This allows us to detect break-to-debugger events
1382	 * while the console device is closed.
1383	 */
1384	if (com->unit != comconsole)
1385#endif
1386	{
1387		sio_setreg(com, com_ier, 0);
1388		if (tp->t_cflag & HUPCL
1389		    /*
1390		     * XXX we will miss any carrier drop between here and the
1391		     * next open.  Perhaps we should watch DCD even when the
1392		     * port is closed; it is not sufficient to check it at
1393		     * the next open because it might go up and down while
1394		     * we're not watching.
1395		     */
1396		    || (!com->active_out
1397		        && !(com->prev_modem_status & MSR_DCD)
1398		        && !(com->it_in.c_cflag & CLOCAL))
1399		    || !(tp->t_state & TS_ISOPEN)) {
1400			(void)commctl(com, TIOCM_DTR, DMBIC);
1401			if (com->dtr_wait != 0 && !(com->state & CS_DTR_OFF)) {
1402				timeout(siodtrwakeup, com, com->dtr_wait);
1403				com->state |= CS_DTR_OFF;
1404			}
1405		}
1406	}
1407	if (com->hasfifo) {
1408		/*
1409		 * Disable fifos so that they are off after controlled
1410		 * reboots.  Some BIOSes fail to detect 16550s when the
1411		 * fifos are enabled.
1412		 */
1413		sio_setreg(com, com_fifo, 0);
1414	}
1415	com->active_out = FALSE;
1416	wakeup(&com->active_out);
1417	wakeup(TSA_CARR_ON(tp));	/* restart any wopeners */
1418	splx(s);
1419}
1420
1421static int
1422sioread(dev, uio, flag)
1423	dev_t		dev;
1424	struct uio	*uio;
1425	int		flag;
1426{
1427	int		mynor;
1428	struct com_s	*com;
1429
1430	mynor = minor(dev);
1431	if (mynor & CONTROL_MASK)
1432		return (ENODEV);
1433	com = com_addr(MINOR_TO_UNIT(mynor));
1434	if (com == NULL || com->gone)
1435		return (ENODEV);
1436	return ((*linesw[com->tp->t_line].l_read)(com->tp, uio, flag));
1437}
1438
1439static int
1440siowrite(dev, uio, flag)
1441	dev_t		dev;
1442	struct uio	*uio;
1443	int		flag;
1444{
1445	int		mynor;
1446	struct com_s	*com;
1447	int		unit;
1448
1449	mynor = minor(dev);
1450	if (mynor & CONTROL_MASK)
1451		return (ENODEV);
1452
1453	unit = MINOR_TO_UNIT(mynor);
1454	com = com_addr(unit);
1455	if (com == NULL || com->gone)
1456		return (ENODEV);
1457	/*
1458	 * (XXX) We disallow virtual consoles if the physical console is
1459	 * a serial port.  This is in case there is a display attached that
1460	 * is not the console.  In that situation we don't need/want the X
1461	 * server taking over the console.
1462	 */
1463	if (constty != NULL && unit == comconsole)
1464		constty = NULL;
1465	return ((*linesw[com->tp->t_line].l_write)(com->tp, uio, flag));
1466}
1467
1468static void
1469siobusycheck(chan)
1470	void	*chan;
1471{
1472	struct com_s	*com;
1473	int		s;
1474
1475	com = (struct com_s *)chan;
1476
1477	/*
1478	 * Clear TS_BUSY if low-level output is complete.
1479	 * spl locking is sufficient because siointr1() does not set CS_BUSY.
1480	 * If siointr1() clears CS_BUSY after we look at it, then we'll get
1481	 * called again.  Reading the line status port outside of siointr1()
1482	 * is safe because CS_BUSY is clear so there are no output interrupts
1483	 * to lose.
1484	 */
1485	s = spltty();
1486	if (com->state & CS_BUSY)
1487		com->extra_state &= ~CSE_BUSYCHECK;	/* False alarm. */
1488	else if ((inb(com->line_status_port) & (LSR_TSRE | LSR_TXRDY))
1489	    == (LSR_TSRE | LSR_TXRDY)) {
1490		com->tp->t_state &= ~TS_BUSY;
1491		ttwwakeup(com->tp);
1492		com->extra_state &= ~CSE_BUSYCHECK;
1493	} else
1494		timeout(siobusycheck, com, hz / 100);
1495	splx(s);
1496}
1497
1498static void
1499siodtrwakeup(chan)
1500	void	*chan;
1501{
1502	struct com_s	*com;
1503
1504	com = (struct com_s *)chan;
1505	com->state &= ~CS_DTR_OFF;
1506	wakeup(&com->dtr_wait);
1507}
1508
1509/*
1510 * Call this function with the sio_lock mutex held.  It will return with the
1511 * lock still held.
1512 */
1513static void
1514sioinput(com)
1515	struct com_s	*com;
1516{
1517	u_char		*buf;
1518	int		incc;
1519	u_char		line_status;
1520	int		recv_data;
1521	struct tty	*tp;
1522
1523	buf = com->ibuf;
1524	tp = com->tp;
1525	if (!(tp->t_state & TS_ISOPEN) || !(tp->t_cflag & CREAD)) {
1526		com_events -= (com->iptr - com->ibuf);
1527		com->iptr = com->ibuf;
1528		return;
1529	}
1530	if (tp->t_state & TS_CAN_BYPASS_L_RINT) {
1531		/*
1532		 * Avoid the grotesquely inefficient lineswitch routine
1533		 * (ttyinput) in "raw" mode.  It usually takes about 450
1534		 * instructions (that's without canonical processing or echo!).
1535		 * slinput is reasonably fast (usually 40 instructions plus
1536		 * call overhead).
1537		 */
1538		do {
1539			/*
1540			 * This may look odd, but it is using save-and-enable
1541			 * semantics instead of the save-and-disable semantics
1542			 * that are used everywhere else.
1543			 */
1544			mtx_unlock_spin(&sio_lock);
1545			incc = com->iptr - buf;
1546			if (tp->t_rawq.c_cc + incc > tp->t_ihiwat
1547			    && (com->state & CS_RTS_IFLOW
1548				|| tp->t_iflag & IXOFF)
1549			    && !(tp->t_state & TS_TBLOCK))
1550				ttyblock(tp);
1551			com->delta_error_counts[CE_TTY_BUF_OVERFLOW]
1552				+= b_to_q((char *)buf, incc, &tp->t_rawq);
1553			buf += incc;
1554			tk_nin += incc;
1555			tk_rawcc += incc;
1556			tp->t_rawcc += incc;
1557			ttwakeup(tp);
1558			if (tp->t_state & TS_TTSTOP
1559			    && (tp->t_iflag & IXANY
1560				|| tp->t_cc[VSTART] == tp->t_cc[VSTOP])) {
1561				tp->t_state &= ~TS_TTSTOP;
1562				tp->t_lflag &= ~FLUSHO;
1563				comstart(tp);
1564			}
1565			mtx_lock_spin(&sio_lock);
1566		} while (buf < com->iptr);
1567	} else {
1568		do {
1569			/*
1570			 * This may look odd, but it is using save-and-enable
1571			 * semantics instead of the save-and-disable semantics
1572			 * that are used everywhere else.
1573			 */
1574			mtx_unlock_spin(&sio_lock);
1575			line_status = buf[com->ierroff];
1576			recv_data = *buf++;
1577			if (line_status
1578			    & (LSR_BI | LSR_FE | LSR_OE | LSR_PE)) {
1579				if (line_status & LSR_BI)
1580					recv_data |= TTY_BI;
1581				if (line_status & LSR_FE)
1582					recv_data |= TTY_FE;
1583				if (line_status & LSR_OE)
1584					recv_data |= TTY_OE;
1585				if (line_status & LSR_PE)
1586					recv_data |= TTY_PE;
1587			}
1588			(*linesw[tp->t_line].l_rint)(recv_data, tp);
1589			mtx_lock_spin(&sio_lock);
1590		} while (buf < com->iptr);
1591	}
1592	com_events -= (com->iptr - com->ibuf);
1593	com->iptr = com->ibuf;
1594
1595	/*
1596	 * There is now room for another low-level buffer full of input,
1597	 * so enable RTS if it is now disabled and there is room in the
1598	 * high-level buffer.
1599	 */
1600	if ((com->state & CS_RTS_IFLOW) && !(com->mcr_image & MCR_RTS) &&
1601	    !(tp->t_state & TS_TBLOCK))
1602		outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
1603}
1604
1605void
1606siointr(arg)
1607	void		*arg;
1608{
1609	struct com_s	*com;
1610
1611#ifndef COM_MULTIPORT
1612	com = (struct com_s *)arg;
1613
1614	mtx_lock_spin(&sio_lock);
1615	siointr1(com);
1616	mtx_unlock_spin(&sio_lock);
1617#else /* COM_MULTIPORT */
1618	bool_t		possibly_more_intrs;
1619	int		unit;
1620
1621	/*
1622	 * Loop until there is no activity on any port.  This is necessary
1623	 * to get an interrupt edge more than to avoid another interrupt.
1624	 * If the IRQ signal is just an OR of the IRQ signals from several
1625	 * devices, then the edge from one may be lost because another is
1626	 * on.
1627	 */
1628	mtx_lock_spin(&sio_lock);
1629	do {
1630		possibly_more_intrs = FALSE;
1631		for (unit = 0; unit < sio_numunits; ++unit) {
1632			com = com_addr(unit);
1633			/*
1634			 * XXX COM_LOCK();
1635			 * would it work here, or be counter-productive?
1636			 */
1637			if (com != NULL
1638			    && !com->gone
1639			    && (inb(com->int_id_port) & IIR_IMASK)
1640			       != IIR_NOPEND) {
1641				siointr1(com);
1642				possibly_more_intrs = TRUE;
1643			}
1644			/* XXX COM_UNLOCK(); */
1645		}
1646	} while (possibly_more_intrs);
1647	mtx_unlock_spin(&sio_lock);
1648#endif /* COM_MULTIPORT */
1649}
1650
1651static void
1652siointr1(com)
1653	struct com_s	*com;
1654{
1655	u_char	line_status;
1656	u_char	modem_status;
1657	u_char	*ioptr;
1658	u_char	recv_data;
1659	u_char	int_ctl;
1660	u_char	int_ctl_new;
1661	struct	timecounter *tc;
1662	u_int	count;
1663
1664	int_ctl = inb(com->intr_ctl_port);
1665	int_ctl_new = int_ctl;
1666
1667	while (!com->gone) {
1668		if (com->pps.ppsparam.mode & PPS_CAPTUREBOTH) {
1669			modem_status = inb(com->modem_status_port);
1670		        if ((modem_status ^ com->last_modem_status) & MSR_DCD) {
1671				tc = timecounter;
1672				count = tc->tc_get_timecount(tc);
1673				pps_event(&com->pps, tc, count,
1674				    (modem_status & MSR_DCD) ?
1675				    PPS_CAPTUREASSERT : PPS_CAPTURECLEAR);
1676			}
1677		}
1678		line_status = inb(com->line_status_port);
1679
1680		/* input event? (check first to help avoid overruns) */
1681		while (line_status & LSR_RCV_MASK) {
1682			/* break/unnattached error bits or real input? */
1683			if (!(line_status & LSR_RXRDY))
1684				recv_data = 0;
1685			else
1686				recv_data = inb(com->data_port);
1687#if defined(DDB) && defined(ALT_BREAK_TO_DEBUGGER)
1688			/*
1689			 * Solaris implements a new BREAK which is initiated
1690			 * by a character sequence CR ~ ^b which is similar
1691			 * to a familiar pattern used on Sun servers by the
1692			 * Remote Console.
1693			 */
1694#define	KEY_CRTLB	2	/* ^B */
1695#define	KEY_CR		13	/* CR '\r' */
1696#define	KEY_TILDE	126	/* ~ */
1697
1698			if (com->unit == comconsole) {
1699				static int brk_state1 = 0, brk_state2 = 0;
1700				if (recv_data == KEY_CR) {
1701					brk_state1 = recv_data;
1702					brk_state2 = 0;
1703				} else if (brk_state1 == KEY_CR
1704					   && (recv_data == KEY_TILDE
1705					       || recv_data == KEY_CRTLB)) {
1706					if (recv_data == KEY_TILDE)
1707						brk_state2 = recv_data;
1708					else if (brk_state2 == KEY_TILDE
1709						 && recv_data == KEY_CRTLB) {
1710							breakpoint();
1711							brk_state1 = 0;
1712							brk_state2 = 0;
1713							goto cont;
1714					} else
1715						brk_state2 = 0;
1716				} else
1717					brk_state1 = 0;
1718			}
1719#endif
1720			if (line_status & (LSR_BI | LSR_FE | LSR_PE)) {
1721				/*
1722				 * Don't store BI if IGNBRK or FE/PE if IGNPAR.
1723				 * Otherwise, push the work to a higher level
1724				 * (to handle PARMRK) if we're bypassing.
1725				 * Otherwise, convert BI/FE and PE+INPCK to 0.
1726				 *
1727				 * This makes bypassing work right in the
1728				 * usual "raw" case (IGNBRK set, and IGNPAR
1729				 * and INPCK clear).
1730				 *
1731				 * Note: BI together with FE/PE means just BI.
1732				 */
1733				if (line_status & LSR_BI) {
1734#if defined(DDB) && defined(BREAK_TO_DEBUGGER)
1735					if (com->unit == comconsole) {
1736						breakpoint();
1737						goto cont;
1738					}
1739#endif
1740					if (com->tp == NULL
1741					    || com->tp->t_iflag & IGNBRK)
1742						goto cont;
1743				} else {
1744					if (com->tp == NULL
1745					    || com->tp->t_iflag & IGNPAR)
1746						goto cont;
1747				}
1748				if (com->tp->t_state & TS_CAN_BYPASS_L_RINT
1749				    && (line_status & (LSR_BI | LSR_FE)
1750					|| com->tp->t_iflag & INPCK))
1751					recv_data = 0;
1752			}
1753			++com->bytes_in;
1754			if (com->hotchar != 0 && recv_data == com->hotchar)
1755				swi_sched(sio_fast_ih, 0);
1756			ioptr = com->iptr;
1757			if (ioptr >= com->ibufend)
1758				CE_RECORD(com, CE_INTERRUPT_BUF_OVERFLOW);
1759			else {
1760				if (com->do_timestamp)
1761					microtime(&com->timestamp);
1762				++com_events;
1763				swi_sched(sio_slow_ih, SWI_DELAY);
1764#if 0 /* for testing input latency vs efficiency */
1765if (com->iptr - com->ibuf == 8)
1766	swi_sched(sio_fast_ih, 0);
1767#endif
1768				ioptr[0] = recv_data;
1769				ioptr[com->ierroff] = line_status;
1770				com->iptr = ++ioptr;
1771				if (ioptr == com->ihighwater
1772				    && com->state & CS_RTS_IFLOW)
1773					outb(com->modem_ctl_port,
1774					     com->mcr_image &= ~MCR_RTS);
1775				if (line_status & LSR_OE)
1776					CE_RECORD(com, CE_OVERRUN);
1777			}
1778cont:
1779			/*
1780			 * "& 0x7F" is to avoid the gcc-1.40 generating a slow
1781			 * jump from the top of the loop to here
1782			 */
1783			line_status = inb(com->line_status_port) & 0x7F;
1784		}
1785
1786		/* modem status change? (always check before doing output) */
1787		modem_status = inb(com->modem_status_port);
1788		if (modem_status != com->last_modem_status) {
1789			if (com->do_dcd_timestamp
1790			    && !(com->last_modem_status & MSR_DCD)
1791			    && modem_status & MSR_DCD)
1792				microtime(&com->dcd_timestamp);
1793
1794			/*
1795			 * Schedule high level to handle DCD changes.  Note
1796			 * that we don't use the delta bits anywhere.  Some
1797			 * UARTs mess them up, and it's easy to remember the
1798			 * previous bits and calculate the delta.
1799			 */
1800			com->last_modem_status = modem_status;
1801			if (!(com->state & CS_CHECKMSR)) {
1802				com_events += LOTS_OF_EVENTS;
1803				com->state |= CS_CHECKMSR;
1804				swi_sched(sio_fast_ih, 0);
1805			}
1806
1807			/* handle CTS change immediately for crisp flow ctl */
1808			if (com->state & CS_CTS_OFLOW) {
1809				if (modem_status & MSR_CTS)
1810					com->state |= CS_ODEVREADY;
1811				else
1812					com->state &= ~CS_ODEVREADY;
1813			}
1814		}
1815
1816		/* output queued and everything ready? */
1817		if (line_status & LSR_TXRDY
1818		    && com->state >= (CS_BUSY | CS_TTGO | CS_ODEVREADY)) {
1819			ioptr = com->obufq.l_head;
1820			if (com->tx_fifo_size > 1) {
1821				u_int	ocount;
1822
1823				ocount = com->obufq.l_tail - ioptr;
1824				if (ocount > com->tx_fifo_size)
1825					ocount = com->tx_fifo_size;
1826				com->bytes_out += ocount;
1827				do
1828					outb(com->data_port, *ioptr++);
1829				while (--ocount != 0);
1830			} else {
1831				outb(com->data_port, *ioptr++);
1832				++com->bytes_out;
1833			}
1834			com->obufq.l_head = ioptr;
1835			if (COM_IIR_TXRDYBUG(com->flags)) {
1836				int_ctl_new = int_ctl | IER_ETXRDY;
1837			}
1838			if (ioptr >= com->obufq.l_tail) {
1839				struct lbq	*qp;
1840
1841				qp = com->obufq.l_next;
1842				qp->l_queued = FALSE;
1843				qp = qp->l_next;
1844				if (qp != NULL) {
1845					com->obufq.l_head = qp->l_head;
1846					com->obufq.l_tail = qp->l_tail;
1847					com->obufq.l_next = qp;
1848				} else {
1849					/* output just completed */
1850					if (COM_IIR_TXRDYBUG(com->flags)) {
1851						int_ctl_new = int_ctl & ~IER_ETXRDY;
1852					}
1853					com->state &= ~CS_BUSY;
1854				}
1855				if (!(com->state & CS_ODONE)) {
1856					com_events += LOTS_OF_EVENTS;
1857					com->state |= CS_ODONE;
1858					/* handle at high level ASAP */
1859					swi_sched(sio_fast_ih, 0);
1860				}
1861			}
1862			if (COM_IIR_TXRDYBUG(com->flags) && (int_ctl != int_ctl_new)) {
1863				outb(com->intr_ctl_port, int_ctl_new);
1864			}
1865		}
1866
1867		/* finished? */
1868#ifndef COM_MULTIPORT
1869		if ((inb(com->int_id_port) & IIR_IMASK) == IIR_NOPEND)
1870#endif /* COM_MULTIPORT */
1871			return;
1872	}
1873}
1874
1875static int
1876sioioctl(dev, cmd, data, flag, td)
1877	dev_t		dev;
1878	u_long		cmd;
1879	caddr_t		data;
1880	int		flag;
1881	struct thread	*td;
1882{
1883	struct com_s	*com;
1884	int		error;
1885	int		mynor;
1886	int		s;
1887	struct tty	*tp;
1888#if defined(COMPAT_43) || defined(COMPAT_SUNOS)
1889	u_long		oldcmd;
1890	struct termios	term;
1891#endif
1892
1893	mynor = minor(dev);
1894	com = com_addr(MINOR_TO_UNIT(mynor));
1895	if (com == NULL || com->gone)
1896		return (ENODEV);
1897	if (mynor & CONTROL_MASK) {
1898		struct termios	*ct;
1899
1900		switch (mynor & CONTROL_MASK) {
1901		case CONTROL_INIT_STATE:
1902			ct = mynor & CALLOUT_MASK ? &com->it_out : &com->it_in;
1903			break;
1904		case CONTROL_LOCK_STATE:
1905			ct = mynor & CALLOUT_MASK ? &com->lt_out : &com->lt_in;
1906			break;
1907		default:
1908			return (ENODEV);	/* /dev/nodev */
1909		}
1910		switch (cmd) {
1911		case TIOCSETA:
1912			error = suser_td(td);
1913			if (error != 0)
1914				return (error);
1915			*ct = *(struct termios *)data;
1916			return (0);
1917		case TIOCGETA:
1918			*(struct termios *)data = *ct;
1919			return (0);
1920		case TIOCGETD:
1921			*(int *)data = TTYDISC;
1922			return (0);
1923		case TIOCGWINSZ:
1924			bzero(data, sizeof(struct winsize));
1925			return (0);
1926		default:
1927			return (ENOTTY);
1928		}
1929	}
1930	tp = com->tp;
1931#if defined(COMPAT_43) || defined(COMPAT_SUNOS)
1932	term = tp->t_termios;
1933	oldcmd = cmd;
1934	error = ttsetcompat(tp, &cmd, data, &term);
1935	if (error != 0)
1936		return (error);
1937	if (cmd != oldcmd)
1938		data = (caddr_t)&term;
1939#endif
1940	if (cmd == TIOCSETA || cmd == TIOCSETAW || cmd == TIOCSETAF) {
1941		int	cc;
1942		struct termios *dt = (struct termios *)data;
1943		struct termios *lt = mynor & CALLOUT_MASK
1944				     ? &com->lt_out : &com->lt_in;
1945
1946		dt->c_iflag = (tp->t_iflag & lt->c_iflag)
1947			      | (dt->c_iflag & ~lt->c_iflag);
1948		dt->c_oflag = (tp->t_oflag & lt->c_oflag)
1949			      | (dt->c_oflag & ~lt->c_oflag);
1950		dt->c_cflag = (tp->t_cflag & lt->c_cflag)
1951			      | (dt->c_cflag & ~lt->c_cflag);
1952		dt->c_lflag = (tp->t_lflag & lt->c_lflag)
1953			      | (dt->c_lflag & ~lt->c_lflag);
1954		for (cc = 0; cc < NCCS; ++cc)
1955			if (lt->c_cc[cc] != 0)
1956				dt->c_cc[cc] = tp->t_cc[cc];
1957		if (lt->c_ispeed != 0)
1958			dt->c_ispeed = tp->t_ispeed;
1959		if (lt->c_ospeed != 0)
1960			dt->c_ospeed = tp->t_ospeed;
1961	}
1962	error = (*linesw[tp->t_line].l_ioctl)(tp, cmd, data, flag, td);
1963	if (error != ENOIOCTL)
1964		return (error);
1965	s = spltty();
1966	error = ttioctl(tp, cmd, data, flag);
1967	disc_optim(tp, &tp->t_termios, com);
1968	if (error != ENOIOCTL) {
1969		splx(s);
1970		return (error);
1971	}
1972	switch (cmd) {
1973	case TIOCSBRK:
1974		sio_setreg(com, com_cfcr, com->cfcr_image |= CFCR_SBREAK);
1975		break;
1976	case TIOCCBRK:
1977		sio_setreg(com, com_cfcr, com->cfcr_image &= ~CFCR_SBREAK);
1978		break;
1979	case TIOCSDTR:
1980		(void)commctl(com, TIOCM_DTR, DMBIS);
1981		break;
1982	case TIOCCDTR:
1983		(void)commctl(com, TIOCM_DTR, DMBIC);
1984		break;
1985	/*
1986	 * XXX should disallow changing MCR_RTS if CS_RTS_IFLOW is set.  The
1987	 * changes get undone on the next call to comparam().
1988	 */
1989	case TIOCMSET:
1990		(void)commctl(com, *(int *)data, DMSET);
1991		break;
1992	case TIOCMBIS:
1993		(void)commctl(com, *(int *)data, DMBIS);
1994		break;
1995	case TIOCMBIC:
1996		(void)commctl(com, *(int *)data, DMBIC);
1997		break;
1998	case TIOCMGET:
1999		*(int *)data = commctl(com, 0, DMGET);
2000		break;
2001	case TIOCMSDTRWAIT:
2002		/* must be root since the wait applies to following logins */
2003		error = suser_td(td);
2004		if (error != 0) {
2005			splx(s);
2006			return (error);
2007		}
2008		com->dtr_wait = *(int *)data * hz / 100;
2009		break;
2010	case TIOCMGDTRWAIT:
2011		*(int *)data = com->dtr_wait * 100 / hz;
2012		break;
2013	case TIOCTIMESTAMP:
2014		com->do_timestamp = TRUE;
2015		*(struct timeval *)data = com->timestamp;
2016		break;
2017	case TIOCDCDTIMESTAMP:
2018		com->do_dcd_timestamp = TRUE;
2019		*(struct timeval *)data = com->dcd_timestamp;
2020		break;
2021	default:
2022		splx(s);
2023		error = pps_ioctl(cmd, data, &com->pps);
2024		if (error == ENODEV)
2025			error = ENOTTY;
2026		return (error);
2027	}
2028	splx(s);
2029	return (0);
2030}
2031
2032/* software interrupt handler for SWI_TTY */
2033static void
2034siopoll(void *dummy)
2035{
2036	int		unit;
2037
2038	if (com_events == 0)
2039		return;
2040repeat:
2041	for (unit = 0; unit < sio_numunits; ++unit) {
2042		struct com_s	*com;
2043		int		incc;
2044		struct tty	*tp;
2045
2046		com = com_addr(unit);
2047		if (com == NULL)
2048			continue;
2049		tp = com->tp;
2050		if (tp == NULL || com->gone) {
2051			/*
2052			 * Discard any events related to never-opened or
2053			 * going-away devices.
2054			 */
2055			mtx_lock_spin(&sio_lock);
2056			incc = com->iptr - com->ibuf;
2057			com->iptr = com->ibuf;
2058			if (com->state & CS_CHECKMSR) {
2059				incc += LOTS_OF_EVENTS;
2060				com->state &= ~CS_CHECKMSR;
2061			}
2062			com_events -= incc;
2063			mtx_unlock_spin(&sio_lock);
2064			continue;
2065		}
2066		if (com->iptr != com->ibuf) {
2067			mtx_lock_spin(&sio_lock);
2068			sioinput(com);
2069			mtx_unlock_spin(&sio_lock);
2070		}
2071		if (com->state & CS_CHECKMSR) {
2072			u_char	delta_modem_status;
2073
2074			mtx_lock_spin(&sio_lock);
2075			delta_modem_status = com->last_modem_status
2076					     ^ com->prev_modem_status;
2077			com->prev_modem_status = com->last_modem_status;
2078			com_events -= LOTS_OF_EVENTS;
2079			com->state &= ~CS_CHECKMSR;
2080			mtx_unlock_spin(&sio_lock);
2081			if (delta_modem_status & MSR_DCD)
2082				(*linesw[tp->t_line].l_modem)
2083					(tp, com->prev_modem_status & MSR_DCD);
2084		}
2085		if (com->state & CS_ODONE) {
2086			mtx_lock_spin(&sio_lock);
2087			com_events -= LOTS_OF_EVENTS;
2088			com->state &= ~CS_ODONE;
2089			mtx_unlock_spin(&sio_lock);
2090			if (!(com->state & CS_BUSY)
2091			    && !(com->extra_state & CSE_BUSYCHECK)) {
2092				timeout(siobusycheck, com, hz / 100);
2093				com->extra_state |= CSE_BUSYCHECK;
2094			}
2095			(*linesw[tp->t_line].l_start)(tp);
2096		}
2097		if (com_events == 0)
2098			break;
2099	}
2100	if (com_events >= LOTS_OF_EVENTS)
2101		goto repeat;
2102}
2103
2104static int
2105comparam(tp, t)
2106	struct tty	*tp;
2107	struct termios	*t;
2108{
2109	u_int		cfcr;
2110	int		cflag;
2111	struct com_s	*com;
2112	int		divisor;
2113	u_char		dlbh;
2114	u_char		dlbl;
2115	int		s;
2116	int		unit;
2117
2118	/* do historical conversions */
2119	if (t->c_ispeed == 0)
2120		t->c_ispeed = t->c_ospeed;
2121
2122	/* check requested parameters */
2123	divisor = ttspeedtab(t->c_ospeed, comspeedtab);
2124	if (divisor < 0 || (divisor > 0 && t->c_ispeed != t->c_ospeed))
2125		return (EINVAL);
2126
2127	/* parameters are OK, convert them to the com struct and the device */
2128	unit = DEV_TO_UNIT(tp->t_dev);
2129	com = com_addr(unit);
2130	if (com == NULL)
2131		return (ENODEV);
2132	s = spltty();
2133	if (divisor == 0)
2134		(void)commctl(com, TIOCM_DTR, DMBIC);	/* hang up line */
2135	else
2136		(void)commctl(com, TIOCM_DTR, DMBIS);
2137	cflag = t->c_cflag;
2138	switch (cflag & CSIZE) {
2139	case CS5:
2140		cfcr = CFCR_5BITS;
2141		break;
2142	case CS6:
2143		cfcr = CFCR_6BITS;
2144		break;
2145	case CS7:
2146		cfcr = CFCR_7BITS;
2147		break;
2148	default:
2149		cfcr = CFCR_8BITS;
2150		break;
2151	}
2152	if (cflag & PARENB) {
2153		cfcr |= CFCR_PENAB;
2154		if (!(cflag & PARODD))
2155			cfcr |= CFCR_PEVEN;
2156	}
2157	if (cflag & CSTOPB)
2158		cfcr |= CFCR_STOPB;
2159
2160	if (com->hasfifo && divisor != 0) {
2161		/*
2162		 * Use a fifo trigger level low enough so that the input
2163		 * latency from the fifo is less than about 16 msec and
2164		 * the total latency is less than about 30 msec.  These
2165		 * latencies are reasonable for humans.  Serial comms
2166		 * protocols shouldn't expect anything better since modem
2167		 * latencies are larger.
2168		 *
2169		 * The fifo trigger level cannot be set at RX_HIGH for high
2170		 * speed connections without further work on reducing
2171		 * interrupt disablement times in other parts of the system,
2172		 * without producing silo overflow errors.
2173		 */
2174		com->fifo_image = t->c_ospeed <= 4800
2175				  ? FIFO_ENABLE : FIFO_ENABLE | FIFO_RX_MEDH;
2176#ifdef COM_ESP
2177		/*
2178		 * The Hayes ESP card needs the fifo DMA mode bit set
2179		 * in compatibility mode.  If not, it will interrupt
2180		 * for each character received.
2181		 */
2182		if (com->esp)
2183			com->fifo_image |= FIFO_DMA_MODE;
2184#endif
2185		sio_setreg(com, com_fifo, com->fifo_image);
2186	}
2187
2188	/*
2189	 * This returns with interrupts disabled so that we can complete
2190	 * the speed change atomically.  Keeping interrupts disabled is
2191	 * especially important while com_data is hidden.
2192	 */
2193	(void) siosetwater(com, t->c_ispeed);
2194
2195	if (divisor != 0) {
2196		sio_setreg(com, com_cfcr, cfcr | CFCR_DLAB);
2197		/*
2198		 * Only set the divisor registers if they would change,
2199		 * since on some 16550 incompatibles (UMC8669F), setting
2200		 * them while input is arriving them loses sync until
2201		 * data stops arriving.
2202		 */
2203		dlbl = divisor & 0xFF;
2204		if (sio_getreg(com, com_dlbl) != dlbl)
2205			sio_setreg(com, com_dlbl, dlbl);
2206		dlbh = (u_int) divisor >> 8;
2207		if (sio_getreg(com, com_dlbh) != dlbh)
2208			sio_setreg(com, com_dlbh, dlbh);
2209	}
2210
2211	sio_setreg(com, com_cfcr, com->cfcr_image = cfcr);
2212
2213	if (!(tp->t_state & TS_TTSTOP))
2214		com->state |= CS_TTGO;
2215
2216	if (cflag & CRTS_IFLOW) {
2217		if (com->st16650a) {
2218			sio_setreg(com, com_cfcr, 0xbf);
2219			sio_setreg(com, com_fifo,
2220				   sio_getreg(com, com_fifo) | 0x40);
2221		}
2222		com->state |= CS_RTS_IFLOW;
2223		/*
2224		 * If CS_RTS_IFLOW just changed from off to on, the change
2225		 * needs to be propagated to MCR_RTS.  This isn't urgent,
2226		 * so do it later by calling comstart() instead of repeating
2227		 * a lot of code from comstart() here.
2228		 */
2229	} else if (com->state & CS_RTS_IFLOW) {
2230		com->state &= ~CS_RTS_IFLOW;
2231		/*
2232		 * CS_RTS_IFLOW just changed from on to off.  Force MCR_RTS
2233		 * on here, since comstart() won't do it later.
2234		 */
2235		outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
2236		if (com->st16650a) {
2237			sio_setreg(com, com_cfcr, 0xbf);
2238			sio_setreg(com, com_fifo,
2239				   sio_getreg(com, com_fifo) & ~0x40);
2240		}
2241	}
2242
2243
2244	/*
2245	 * Set up state to handle output flow control.
2246	 * XXX - worth handling MDMBUF (DCD) flow control at the lowest level?
2247	 * Now has 10+ msec latency, while CTS flow has 50- usec latency.
2248	 */
2249	com->state |= CS_ODEVREADY;
2250	com->state &= ~CS_CTS_OFLOW;
2251	if (cflag & CCTS_OFLOW) {
2252		com->state |= CS_CTS_OFLOW;
2253		if (!(com->last_modem_status & MSR_CTS))
2254			com->state &= ~CS_ODEVREADY;
2255		if (com->st16650a) {
2256			sio_setreg(com, com_cfcr, 0xbf);
2257			sio_setreg(com, com_fifo,
2258				   sio_getreg(com, com_fifo) | 0x80);
2259		}
2260	} else {
2261		if (com->st16650a) {
2262			sio_setreg(com, com_cfcr, 0xbf);
2263			sio_setreg(com, com_fifo,
2264				   sio_getreg(com, com_fifo) & ~0x80);
2265		}
2266	}
2267
2268	sio_setreg(com, com_cfcr, com->cfcr_image);
2269
2270	/* XXX shouldn't call functions while intrs are disabled. */
2271	disc_optim(tp, t, com);
2272	/*
2273	 * Recover from fiddling with CS_TTGO.  We used to call siointr1()
2274	 * unconditionally, but that defeated the careful discarding of
2275	 * stale input in sioopen().
2276	 */
2277	if (com->state >= (CS_BUSY | CS_TTGO))
2278		siointr1(com);
2279
2280	mtx_unlock_spin(&sio_lock);
2281	splx(s);
2282	comstart(tp);
2283	if (com->ibufold != NULL) {
2284		free(com->ibufold, M_DEVBUF);
2285		com->ibufold = NULL;
2286	}
2287	return (0);
2288}
2289
2290/*
2291 * This function must be called with the sio_lock mutex released and will
2292 * return with it obtained.
2293 */
2294static int
2295siosetwater(com, speed)
2296	struct com_s	*com;
2297	speed_t		speed;
2298{
2299	int		cp4ticks;
2300	u_char		*ibuf;
2301	int		ibufsize;
2302	struct tty	*tp;
2303
2304	/*
2305	 * Make the buffer size large enough to handle a softtty interrupt
2306	 * latency of about 2 ticks without loss of throughput or data
2307	 * (about 3 ticks if input flow control is not used or not honoured,
2308	 * but a bit less for CS5-CS7 modes).
2309	 */
2310	cp4ticks = speed / 10 / hz * 4;
2311	for (ibufsize = 128; ibufsize < cp4ticks;)
2312		ibufsize <<= 1;
2313	if (ibufsize == com->ibufsize) {
2314		mtx_lock_spin(&sio_lock);
2315		return (0);
2316	}
2317
2318	/*
2319	 * Allocate input buffer.  The extra factor of 2 in the size is
2320	 * to allow for an error byte for each input byte.
2321	 */
2322	ibuf = malloc(2 * ibufsize, M_DEVBUF, M_NOWAIT);
2323	if (ibuf == NULL) {
2324		mtx_lock_spin(&sio_lock);
2325		return (ENOMEM);
2326	}
2327
2328	/* Initialize non-critical variables. */
2329	com->ibufold = com->ibuf;
2330	com->ibufsize = ibufsize;
2331	tp = com->tp;
2332	if (tp != NULL) {
2333		tp->t_ififosize = 2 * ibufsize;
2334		tp->t_ispeedwat = (speed_t)-1;
2335		tp->t_ospeedwat = (speed_t)-1;
2336	}
2337
2338	/*
2339	 * Read current input buffer, if any.  Continue with interrupts
2340	 * disabled.
2341	 */
2342	mtx_lock_spin(&sio_lock);
2343	if (com->iptr != com->ibuf)
2344		sioinput(com);
2345
2346	/*-
2347	 * Initialize critical variables, including input buffer watermarks.
2348	 * The external device is asked to stop sending when the buffer
2349	 * exactly reaches high water, or when the high level requests it.
2350	 * The high level is notified immediately (rather than at a later
2351	 * clock tick) when this watermark is reached.
2352	 * The buffer size is chosen so the watermark should almost never
2353	 * be reached.
2354	 * The low watermark is invisibly 0 since the buffer is always
2355	 * emptied all at once.
2356	 */
2357	com->iptr = com->ibuf = ibuf;
2358	com->ibufend = ibuf + ibufsize;
2359	com->ierroff = ibufsize;
2360	com->ihighwater = ibuf + 3 * ibufsize / 4;
2361	return (0);
2362}
2363
2364static void
2365comstart(tp)
2366	struct tty	*tp;
2367{
2368	struct com_s	*com;
2369	int		s;
2370	int		unit;
2371
2372	unit = DEV_TO_UNIT(tp->t_dev);
2373	com = com_addr(unit);
2374	if (com == NULL)
2375		return;
2376	s = spltty();
2377	mtx_lock_spin(&sio_lock);
2378	if (tp->t_state & TS_TTSTOP)
2379		com->state &= ~CS_TTGO;
2380	else
2381		com->state |= CS_TTGO;
2382	if (tp->t_state & TS_TBLOCK) {
2383		if (com->mcr_image & MCR_RTS && com->state & CS_RTS_IFLOW)
2384			outb(com->modem_ctl_port, com->mcr_image &= ~MCR_RTS);
2385	} else {
2386		if (!(com->mcr_image & MCR_RTS) && com->iptr < com->ihighwater
2387		    && com->state & CS_RTS_IFLOW)
2388			outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
2389	}
2390	mtx_unlock_spin(&sio_lock);
2391	if (tp->t_state & (TS_TIMEOUT | TS_TTSTOP)) {
2392		ttwwakeup(tp);
2393		splx(s);
2394		return;
2395	}
2396	if (tp->t_outq.c_cc != 0) {
2397		struct lbq	*qp;
2398		struct lbq	*next;
2399
2400		if (!com->obufs[0].l_queued) {
2401			com->obufs[0].l_tail
2402			    = com->obuf1 + q_to_b(&tp->t_outq, com->obuf1,
2403						  sizeof com->obuf1);
2404			com->obufs[0].l_next = NULL;
2405			com->obufs[0].l_queued = TRUE;
2406			mtx_lock_spin(&sio_lock);
2407			if (com->state & CS_BUSY) {
2408				qp = com->obufq.l_next;
2409				while ((next = qp->l_next) != NULL)
2410					qp = next;
2411				qp->l_next = &com->obufs[0];
2412			} else {
2413				com->obufq.l_head = com->obufs[0].l_head;
2414				com->obufq.l_tail = com->obufs[0].l_tail;
2415				com->obufq.l_next = &com->obufs[0];
2416				com->state |= CS_BUSY;
2417			}
2418			mtx_unlock_spin(&sio_lock);
2419		}
2420		if (tp->t_outq.c_cc != 0 && !com->obufs[1].l_queued) {
2421			com->obufs[1].l_tail
2422			    = com->obuf2 + q_to_b(&tp->t_outq, com->obuf2,
2423						  sizeof com->obuf2);
2424			com->obufs[1].l_next = NULL;
2425			com->obufs[1].l_queued = TRUE;
2426			mtx_lock_spin(&sio_lock);
2427			if (com->state & CS_BUSY) {
2428				qp = com->obufq.l_next;
2429				while ((next = qp->l_next) != NULL)
2430					qp = next;
2431				qp->l_next = &com->obufs[1];
2432			} else {
2433				com->obufq.l_head = com->obufs[1].l_head;
2434				com->obufq.l_tail = com->obufs[1].l_tail;
2435				com->obufq.l_next = &com->obufs[1];
2436				com->state |= CS_BUSY;
2437			}
2438			mtx_unlock_spin(&sio_lock);
2439		}
2440		tp->t_state |= TS_BUSY;
2441	}
2442	mtx_lock_spin(&sio_lock);
2443	if (com->state >= (CS_BUSY | CS_TTGO))
2444		siointr1(com);	/* fake interrupt to start output */
2445	mtx_unlock_spin(&sio_lock);
2446	ttwwakeup(tp);
2447	splx(s);
2448}
2449
2450static void
2451comstop(tp, rw)
2452	struct tty	*tp;
2453	int		rw;
2454{
2455	struct com_s	*com;
2456
2457	com = com_addr(DEV_TO_UNIT(tp->t_dev));
2458	if (com == NULL || com->gone)
2459		return;
2460	mtx_lock_spin(&sio_lock);
2461	if (rw & FWRITE) {
2462		if (com->hasfifo)
2463#ifdef COM_ESP
2464		    /* XXX avoid h/w bug. */
2465		    if (!com->esp)
2466#endif
2467			sio_setreg(com, com_fifo,
2468				   FIFO_XMT_RST | com->fifo_image);
2469		com->obufs[0].l_queued = FALSE;
2470		com->obufs[1].l_queued = FALSE;
2471		if (com->state & CS_ODONE)
2472			com_events -= LOTS_OF_EVENTS;
2473		com->state &= ~(CS_ODONE | CS_BUSY);
2474		com->tp->t_state &= ~TS_BUSY;
2475	}
2476	if (rw & FREAD) {
2477		if (com->hasfifo)
2478#ifdef COM_ESP
2479		    /* XXX avoid h/w bug. */
2480		    if (!com->esp)
2481#endif
2482			sio_setreg(com, com_fifo,
2483				   FIFO_RCV_RST | com->fifo_image);
2484		com_events -= (com->iptr - com->ibuf);
2485		com->iptr = com->ibuf;
2486	}
2487	mtx_unlock_spin(&sio_lock);
2488	comstart(tp);
2489}
2490
2491static int
2492commctl(com, bits, how)
2493	struct com_s	*com;
2494	int		bits;
2495	int		how;
2496{
2497	int	mcr;
2498	int	msr;
2499
2500	if (how == DMGET) {
2501		bits = TIOCM_LE;	/* XXX - always enabled while open */
2502		mcr = com->mcr_image;
2503		if (mcr & MCR_DTR)
2504			bits |= TIOCM_DTR;
2505		if (mcr & MCR_RTS)
2506			bits |= TIOCM_RTS;
2507		msr = com->prev_modem_status;
2508		if (msr & MSR_CTS)
2509			bits |= TIOCM_CTS;
2510		if (msr & MSR_DCD)
2511			bits |= TIOCM_CD;
2512		if (msr & MSR_DSR)
2513			bits |= TIOCM_DSR;
2514		/*
2515		 * XXX - MSR_RI is naturally volatile, and we make MSR_TERI
2516		 * more volatile by reading the modem status a lot.  Perhaps
2517		 * we should latch both bits until the status is read here.
2518		 */
2519		if (msr & (MSR_RI | MSR_TERI))
2520			bits |= TIOCM_RI;
2521		return (bits);
2522	}
2523	mcr = 0;
2524	if (bits & TIOCM_DTR)
2525		mcr |= MCR_DTR;
2526	if (bits & TIOCM_RTS)
2527		mcr |= MCR_RTS;
2528	if (com->gone)
2529		return(0);
2530	mtx_lock_spin(&sio_lock);
2531	switch (how) {
2532	case DMSET:
2533		outb(com->modem_ctl_port,
2534		     com->mcr_image = mcr | (com->mcr_image & MCR_IENABLE));
2535		break;
2536	case DMBIS:
2537		outb(com->modem_ctl_port, com->mcr_image |= mcr);
2538		break;
2539	case DMBIC:
2540		outb(com->modem_ctl_port, com->mcr_image &= ~mcr);
2541		break;
2542	}
2543	mtx_unlock_spin(&sio_lock);
2544	return (0);
2545}
2546
2547static void
2548siosettimeout()
2549{
2550	struct com_s	*com;
2551	bool_t		someopen;
2552	int		unit;
2553
2554	/*
2555	 * Set our timeout period to 1 second if no polled devices are open.
2556	 * Otherwise set it to max(1/200, 1/hz).
2557	 * Enable timeouts iff some device is open.
2558	 */
2559	untimeout(comwakeup, (void *)NULL, sio_timeout_handle);
2560	sio_timeout = hz;
2561	someopen = FALSE;
2562	for (unit = 0; unit < sio_numunits; ++unit) {
2563		com = com_addr(unit);
2564		if (com != NULL && com->tp != NULL
2565		    && com->tp->t_state & TS_ISOPEN && !com->gone) {
2566			someopen = TRUE;
2567			if (com->poll || com->poll_output) {
2568				sio_timeout = hz > 200 ? hz / 200 : 1;
2569				break;
2570			}
2571		}
2572	}
2573	if (someopen) {
2574		sio_timeouts_until_log = hz / sio_timeout;
2575		sio_timeout_handle = timeout(comwakeup, (void *)NULL,
2576					     sio_timeout);
2577	} else {
2578		/* Flush error messages, if any. */
2579		sio_timeouts_until_log = 1;
2580		comwakeup((void *)NULL);
2581		untimeout(comwakeup, (void *)NULL, sio_timeout_handle);
2582	}
2583}
2584
2585static void
2586comwakeup(chan)
2587	void	*chan;
2588{
2589	struct com_s	*com;
2590	int		unit;
2591
2592	sio_timeout_handle = timeout(comwakeup, (void *)NULL, sio_timeout);
2593
2594	/*
2595	 * Recover from lost output interrupts.
2596	 * Poll any lines that don't use interrupts.
2597	 */
2598	for (unit = 0; unit < sio_numunits; ++unit) {
2599		com = com_addr(unit);
2600		if (com != NULL && !com->gone
2601		    && (com->state >= (CS_BUSY | CS_TTGO) || com->poll)) {
2602			mtx_lock_spin(&sio_lock);
2603			siointr1(com);
2604			mtx_unlock_spin(&sio_lock);
2605		}
2606	}
2607
2608	/*
2609	 * Check for and log errors, but not too often.
2610	 */
2611	if (--sio_timeouts_until_log > 0)
2612		return;
2613	sio_timeouts_until_log = hz / sio_timeout;
2614	for (unit = 0; unit < sio_numunits; ++unit) {
2615		int	errnum;
2616
2617		com = com_addr(unit);
2618		if (com == NULL)
2619			continue;
2620		if (com->gone)
2621			continue;
2622		for (errnum = 0; errnum < CE_NTYPES; ++errnum) {
2623			u_int	delta;
2624			u_long	total;
2625
2626			mtx_lock_spin(&sio_lock);
2627			delta = com->delta_error_counts[errnum];
2628			com->delta_error_counts[errnum] = 0;
2629			mtx_unlock_spin(&sio_lock);
2630			if (delta == 0)
2631				continue;
2632			total = com->error_counts[errnum] += delta;
2633			log(LOG_ERR, "sio%d: %u more %s%s (total %lu)\n",
2634			    unit, delta, error_desc[errnum],
2635			    delta == 1 ? "" : "s", total);
2636		}
2637	}
2638}
2639
2640static void
2641disc_optim(tp, t, com)
2642	struct tty	*tp;
2643	struct termios	*t;
2644	struct com_s	*com;
2645{
2646	if (!(t->c_iflag & (ICRNL | IGNCR | IMAXBEL | INLCR | ISTRIP | IXON))
2647	    && (!(t->c_iflag & BRKINT) || (t->c_iflag & IGNBRK))
2648	    && (!(t->c_iflag & PARMRK)
2649		|| (t->c_iflag & (IGNPAR | IGNBRK)) == (IGNPAR | IGNBRK))
2650	    && !(t->c_lflag & (ECHO | ICANON | IEXTEN | ISIG | PENDIN))
2651	    && linesw[tp->t_line].l_rint == ttyinput)
2652		tp->t_state |= TS_CAN_BYPASS_L_RINT;
2653	else
2654		tp->t_state &= ~TS_CAN_BYPASS_L_RINT;
2655	com->hotchar = linesw[tp->t_line].l_hotchar;
2656}
2657
2658/*
2659 * Following are all routines needed for SIO to act as console
2660 */
2661#include <sys/cons.h>
2662
2663struct siocnstate {
2664	u_char	dlbl;
2665	u_char	dlbh;
2666	u_char	ier;
2667	u_char	cfcr;
2668	u_char	mcr;
2669};
2670
2671#ifndef __alpha__
2672static speed_t siocngetspeed __P((Port_t, struct speedtab *));
2673#endif
2674static void siocnclose	__P((struct siocnstate *sp, Port_t iobase));
2675static void siocnopen	__P((struct siocnstate *sp, Port_t iobase, int speed));
2676static void siocntxwait	__P((Port_t iobase));
2677
2678#ifdef __alpha__
2679int siocnattach __P((int port, int speed));
2680int siogdbattach __P((int port, int speed));
2681int siogdbgetc __P((void));
2682void siogdbputc __P((int c));
2683#else
2684static cn_probe_t siocnprobe;
2685static cn_init_t siocninit;
2686static cn_term_t siocnterm;
2687#endif
2688static cn_checkc_t siocncheckc;
2689static cn_getc_t siocngetc;
2690static cn_putc_t siocnputc;
2691
2692#ifndef __alpha__
2693CONS_DRIVER(sio, siocnprobe, siocninit, siocnterm, siocngetc, siocncheckc,
2694	    siocnputc, NULL);
2695#endif
2696
2697/* To get the GDB related variables */
2698#if DDB > 0
2699#include <ddb/ddb.h>
2700#endif
2701
2702static void
2703siocntxwait(iobase)
2704	Port_t	iobase;
2705{
2706	int	timo;
2707
2708	/*
2709	 * Wait for any pending transmission to finish.  Required to avoid
2710	 * the UART lockup bug when the speed is changed, and for normal
2711	 * transmits.
2712	 */
2713	timo = 100000;
2714	while ((inb(iobase + com_lsr) & (LSR_TSRE | LSR_TXRDY))
2715	       != (LSR_TSRE | LSR_TXRDY) && --timo != 0)
2716		;
2717}
2718
2719#ifndef __alpha__
2720
2721/*
2722 * Read the serial port specified and try to figure out what speed
2723 * it's currently running at.  We're assuming the serial port has
2724 * been initialized and is basicly idle.  This routine is only intended
2725 * to be run at system startup.
2726 *
2727 * If the value read from the serial port doesn't make sense, return 0.
2728 */
2729
2730static speed_t
2731siocngetspeed(iobase, table)
2732	Port_t iobase;
2733	struct speedtab *table;
2734{
2735	int	code;
2736	u_char	dlbh;
2737	u_char	dlbl;
2738	u_char  cfcr;
2739
2740	cfcr = inb(iobase + com_cfcr);
2741	outb(iobase + com_cfcr, CFCR_DLAB | cfcr);
2742
2743	dlbl = inb(iobase + com_dlbl);
2744	dlbh = inb(iobase + com_dlbh);
2745
2746	outb(iobase + com_cfcr, cfcr);
2747
2748	code = dlbh << 8 | dlbl;
2749
2750	for (; table->sp_speed != -1; table++)
2751		if (table->sp_code == code)
2752			return (table->sp_speed);
2753
2754	return (0);	/* didn't match anything sane */
2755}
2756
2757#endif
2758
2759static void
2760siocnopen(sp, iobase, speed)
2761	struct siocnstate	*sp;
2762	Port_t			iobase;
2763	int			speed;
2764{
2765	int	divisor;
2766	u_char	dlbh;
2767	u_char	dlbl;
2768
2769	/*
2770	 * Save all the device control registers except the fifo register
2771	 * and set our default ones (cs8 -parenb speed=comdefaultrate).
2772	 * We can't save the fifo register since it is read-only.
2773	 */
2774	sp->ier = inb(iobase + com_ier);
2775	outb(iobase + com_ier, 0);	/* spltty() doesn't stop siointr() */
2776	siocntxwait(iobase);
2777	sp->cfcr = inb(iobase + com_cfcr);
2778	outb(iobase + com_cfcr, CFCR_DLAB | CFCR_8BITS);
2779	sp->dlbl = inb(iobase + com_dlbl);
2780	sp->dlbh = inb(iobase + com_dlbh);
2781	/*
2782	 * Only set the divisor registers if they would change, since on
2783	 * some 16550 incompatibles (Startech), setting them clears the
2784	 * data input register.  This also reduces the effects of the
2785	 * UMC8669F bug.
2786	 */
2787	divisor = ttspeedtab(speed, comspeedtab);
2788	dlbl = divisor & 0xFF;
2789	if (sp->dlbl != dlbl)
2790		outb(iobase + com_dlbl, dlbl);
2791	dlbh = (u_int) divisor >> 8;
2792	if (sp->dlbh != dlbh)
2793		outb(iobase + com_dlbh, dlbh);
2794	outb(iobase + com_cfcr, CFCR_8BITS);
2795	sp->mcr = inb(iobase + com_mcr);
2796	/*
2797	 * We don't want interrupts, but must be careful not to "disable"
2798	 * them by clearing the MCR_IENABLE bit, since that might cause
2799	 * an interrupt by floating the IRQ line.
2800	 */
2801	outb(iobase + com_mcr, (sp->mcr & MCR_IENABLE) | MCR_DTR | MCR_RTS);
2802}
2803
2804static void
2805siocnclose(sp, iobase)
2806	struct siocnstate	*sp;
2807	Port_t			iobase;
2808{
2809	/*
2810	 * Restore the device control registers.
2811	 */
2812	siocntxwait(iobase);
2813	outb(iobase + com_cfcr, CFCR_DLAB | CFCR_8BITS);
2814	if (sp->dlbl != inb(iobase + com_dlbl))
2815		outb(iobase + com_dlbl, sp->dlbl);
2816	if (sp->dlbh != inb(iobase + com_dlbh))
2817		outb(iobase + com_dlbh, sp->dlbh);
2818	outb(iobase + com_cfcr, sp->cfcr);
2819	/*
2820	 * XXX damp oscillations of MCR_DTR and MCR_RTS by not restoring them.
2821	 */
2822	outb(iobase + com_mcr, sp->mcr | MCR_DTR | MCR_RTS);
2823	outb(iobase + com_ier, sp->ier);
2824}
2825
2826#ifndef __alpha__
2827
2828static void
2829siocnprobe(cp)
2830	struct consdev	*cp;
2831{
2832	speed_t			boot_speed;
2833	u_char			cfcr;
2834	int			s, unit;
2835	struct siocnstate	sp;
2836
2837	/*
2838	 * Find our first enabled console, if any.  If it is a high-level
2839	 * console device, then initialize it and return successfully.
2840	 * If it is a low-level console device, then initialize it and
2841	 * return unsuccessfully.  It must be initialized in both cases
2842	 * for early use by console drivers and debuggers.  Initializing
2843	 * the hardware is not necessary in all cases, since the i/o
2844	 * routines initialize it on the fly, but it is necessary if
2845	 * input might arrive while the hardware is switched back to an
2846	 * uninitialized state.  We can't handle multiple console devices
2847	 * yet because our low-level routines don't take a device arg.
2848	 * We trust the user to set the console flags properly so that we
2849	 * don't need to probe.
2850	 */
2851	cp->cn_pri = CN_DEAD;
2852
2853	for (unit = 0; unit < 16; unit++) { /* XXX need to know how many */
2854		int flags;
2855		int disabled;
2856		if (resource_int_value("sio", unit, "disabled", &disabled) == 0) {
2857			if (disabled)
2858				continue;
2859		}
2860		if (resource_int_value("sio", unit, "flags", &flags))
2861			continue;
2862		if (COM_CONSOLE(flags) || COM_DEBUGGER(flags)) {
2863			int port;
2864			Port_t iobase;
2865
2866			if (resource_int_value("sio", unit, "port", &port))
2867				continue;
2868			iobase = port;
2869			s = spltty();
2870			if (boothowto & RB_SERIAL) {
2871				boot_speed = siocngetspeed(iobase, comspeedtab);
2872				if (boot_speed)
2873					comdefaultrate = boot_speed;
2874			}
2875
2876			/*
2877			 * Initialize the divisor latch.  We can't rely on
2878			 * siocnopen() to do this the first time, since it
2879			 * avoids writing to the latch if the latch appears
2880			 * to have the correct value.  Also, if we didn't
2881			 * just read the speed from the hardware, then we
2882			 * need to set the speed in hardware so that
2883			 * switching it later is null.
2884			 */
2885			cfcr = inb(iobase + com_cfcr);
2886			outb(iobase + com_cfcr, CFCR_DLAB | cfcr);
2887			outb(iobase + com_dlbl,
2888			     COMBRD(comdefaultrate) & 0xff);
2889			outb(iobase + com_dlbh,
2890			     (u_int) COMBRD(comdefaultrate) >> 8);
2891			outb(iobase + com_cfcr, cfcr);
2892
2893			siocnopen(&sp, iobase, comdefaultrate);
2894
2895			splx(s);
2896			if (COM_CONSOLE(flags) && !COM_LLCONSOLE(flags)) {
2897				cp->cn_dev = makedev(CDEV_MAJOR, unit);
2898				cp->cn_pri = COM_FORCECONSOLE(flags)
2899					     || boothowto & RB_SERIAL
2900					     ? CN_REMOTE : CN_NORMAL;
2901				siocniobase = iobase;
2902				siocnunit = unit;
2903			}
2904			if (COM_DEBUGGER(flags)) {
2905				printf("sio%d: gdb debugging port\n", unit);
2906				siogdbiobase = iobase;
2907				siogdbunit = unit;
2908#if DDB > 0
2909				gdbdev = makedev(CDEV_MAJOR, unit);
2910				gdb_getc = siocngetc;
2911				gdb_putc = siocnputc;
2912#endif
2913			}
2914		}
2915	}
2916#ifdef	__i386__
2917#if DDB > 0
2918	/*
2919	 * XXX Ugly Compatability.
2920	 * If no gdb port has been specified, set it to be the console
2921	 * as some configuration files don't specify the gdb port.
2922	 */
2923	if (gdbdev == NODEV && (boothowto & RB_GDB)) {
2924		printf("Warning: no GDB port specified. Defaulting to sio%d.\n",
2925			siocnunit);
2926		printf("Set flag 0x80 on desired GDB port in your\n");
2927		printf("configuration file (currently sio only).\n");
2928		siogdbiobase = siocniobase;
2929		siogdbunit = siocnunit;
2930		gdbdev = makedev(CDEV_MAJOR, siocnunit);
2931		gdb_getc = siocngetc;
2932		gdb_putc = siocnputc;
2933	}
2934#endif
2935#endif
2936}
2937
2938static void
2939siocninit(cp)
2940	struct consdev	*cp;
2941{
2942	comconsole = DEV_TO_UNIT(cp->cn_dev);
2943}
2944
2945static void
2946siocnterm(cp)
2947	struct consdev	*cp;
2948{
2949	comconsole = -1;
2950}
2951
2952#endif
2953
2954#ifdef __alpha__
2955
2956CONS_DRIVER(sio, NULL, NULL, NULL, siocngetc, siocncheckc, siocnputc, NULL);
2957
2958int
2959siocnattach(port, speed)
2960	int port;
2961	int speed;
2962{
2963	int			s;
2964	u_char			cfcr;
2965	struct siocnstate	sp;
2966
2967	siocniobase = port;
2968	comdefaultrate = speed;
2969	sio_consdev.cn_pri = CN_NORMAL;
2970	sio_consdev.cn_dev = makedev(CDEV_MAJOR, 0);
2971
2972	s = spltty();
2973
2974	/*
2975	 * Initialize the divisor latch.  We can't rely on
2976	 * siocnopen() to do this the first time, since it
2977	 * avoids writing to the latch if the latch appears
2978	 * to have the correct value.  Also, if we didn't
2979	 * just read the speed from the hardware, then we
2980	 * need to set the speed in hardware so that
2981	 * switching it later is null.
2982	 */
2983	cfcr = inb(siocniobase + com_cfcr);
2984	outb(siocniobase + com_cfcr, CFCR_DLAB | cfcr);
2985	outb(siocniobase + com_dlbl,
2986	     COMBRD(comdefaultrate) & 0xff);
2987	outb(siocniobase + com_dlbh,
2988	     (u_int) COMBRD(comdefaultrate) >> 8);
2989	outb(siocniobase + com_cfcr, cfcr);
2990
2991	siocnopen(&sp, siocniobase, comdefaultrate);
2992	splx(s);
2993
2994	cnadd(&sio_consdev);
2995	return (0);
2996}
2997
2998int
2999siogdbattach(port, speed)
3000	int port;
3001	int speed;
3002{
3003	int			s;
3004	u_char			cfcr;
3005	struct siocnstate	sp;
3006	int			unit = 1;	/* XXX !!! */
3007
3008	siogdbiobase = port;
3009	gdbdefaultrate = speed;
3010
3011	printf("sio%d: gdb debugging port\n", unit);
3012	siogdbunit = unit;
3013#if DDB > 0
3014	gdbdev = makedev(CDEV_MAJOR, unit);
3015	gdb_getc = siocngetc;
3016	gdb_putc = siocnputc;
3017#endif
3018
3019	s = spltty();
3020
3021	/*
3022	 * Initialize the divisor latch.  We can't rely on
3023	 * siocnopen() to do this the first time, since it
3024	 * avoids writing to the latch if the latch appears
3025	 * to have the correct value.  Also, if we didn't
3026	 * just read the speed from the hardware, then we
3027	 * need to set the speed in hardware so that
3028	 * switching it later is null.
3029	 */
3030	cfcr = inb(siogdbiobase + com_cfcr);
3031	outb(siogdbiobase + com_cfcr, CFCR_DLAB | cfcr);
3032	outb(siogdbiobase + com_dlbl,
3033	     COMBRD(gdbdefaultrate) & 0xff);
3034	outb(siogdbiobase + com_dlbh,
3035	     (u_int) COMBRD(gdbdefaultrate) >> 8);
3036	outb(siogdbiobase + com_cfcr, cfcr);
3037
3038	siocnopen(&sp, siogdbiobase, gdbdefaultrate);
3039	splx(s);
3040
3041	return (0);
3042}
3043
3044#endif
3045
3046static int
3047siocncheckc(dev)
3048	dev_t	dev;
3049{
3050	int	c;
3051	Port_t	iobase;
3052	int	s;
3053	struct siocnstate	sp;
3054
3055	if (minor(dev) == siogdbunit)
3056		iobase = siogdbiobase;
3057	else
3058		iobase = siocniobase;
3059	s = spltty();
3060	siocnopen(&sp, iobase, comdefaultrate);
3061	if (inb(iobase + com_lsr) & LSR_RXRDY)
3062		c = inb(iobase + com_data);
3063	else
3064		c = -1;
3065	siocnclose(&sp, iobase);
3066	splx(s);
3067	return (c);
3068}
3069
3070
3071int
3072siocngetc(dev)
3073	dev_t	dev;
3074{
3075	int	c;
3076	Port_t	iobase;
3077	int	s;
3078	struct siocnstate	sp;
3079
3080	if (minor(dev) == siogdbunit)
3081		iobase = siogdbiobase;
3082	else
3083		iobase = siocniobase;
3084	s = spltty();
3085	siocnopen(&sp, iobase, comdefaultrate);
3086	while (!(inb(iobase + com_lsr) & LSR_RXRDY))
3087		;
3088	c = inb(iobase + com_data);
3089	siocnclose(&sp, iobase);
3090	splx(s);
3091	return (c);
3092}
3093
3094void
3095siocnputc(dev, c)
3096	dev_t	dev;
3097	int	c;
3098{
3099	int	need_unlock;
3100	int	s;
3101	struct siocnstate	sp;
3102	Port_t	iobase;
3103
3104	if (minor(dev) == siogdbunit)
3105		iobase = siogdbiobase;
3106	else
3107		iobase = siocniobase;
3108	s = spltty();
3109	need_unlock = 0;
3110	if (sio_inited == 2 && !mtx_owned(&sio_lock)) {
3111		mtx_lock_spin(&sio_lock);
3112		need_unlock = 1;
3113	}
3114	siocnopen(&sp, iobase, comdefaultrate);
3115	siocntxwait(iobase);
3116	outb(iobase + com_data, c);
3117	siocnclose(&sp, iobase);
3118	if (need_unlock)
3119		mtx_unlock_spin(&sio_lock);
3120	splx(s);
3121}
3122
3123#ifdef __alpha__
3124int
3125siogdbgetc()
3126{
3127	int	c;
3128	Port_t	iobase;
3129	int	s;
3130	struct siocnstate	sp;
3131
3132	iobase = siogdbiobase;
3133	s = spltty();
3134	siocnopen(&sp, iobase, gdbdefaultrate);
3135	while (!(inb(iobase + com_lsr) & LSR_RXRDY))
3136		;
3137	c = inb(iobase + com_data);
3138	siocnclose(&sp, iobase);
3139	splx(s);
3140	return (c);
3141}
3142
3143void
3144siogdbputc(c)
3145	int	c;
3146{
3147	int	s;
3148	struct siocnstate	sp;
3149
3150	s = spltty();
3151	siocnopen(&sp, siogdbiobase, gdbdefaultrate);
3152	siocntxwait(siogdbiobase);
3153	outb(siogdbiobase + com_data, c);
3154	siocnclose(&sp, siogdbiobase);
3155	splx(s);
3156}
3157#endif
3158