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