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