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