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