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