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