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