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