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