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