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