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