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