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