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