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