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