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