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