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