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