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