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