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