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