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