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