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