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