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