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