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