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