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