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