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