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