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