]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/sio/sio.c
Partial merge of the SPDX changes
[FreeBSD/FreeBSD.git] / sys / dev / sio / sio.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1991 The Regents of the University of California.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 4. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *      from: @(#)com.c 7.5 (Berkeley) 5/16/91
32  *      from: i386/isa sio.c,v 1.234
33  */
34
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37
38 #include "opt_compat.h"
39 #include "opt_gdb.h"
40 #include "opt_kdb.h"
41 #include "opt_sio.h"
42
43 /*
44  * Serial driver, based on 386BSD-0.1 com driver.
45  * Mostly rewritten to use pseudo-DMA.
46  * Works for National Semiconductor NS8250-NS16550AF UARTs.
47  * COM driver, based on HP dca driver.
48  *
49  * Changes for PC Card integration:
50  *      - Added PC Card driver table and handlers
51  */
52 #include <sys/param.h>
53 #include <sys/systm.h>
54 #include <sys/bus.h>
55 #include <sys/conf.h>
56 #include <sys/fcntl.h>
57 #include <sys/interrupt.h>
58 #include <sys/kdb.h>
59 #include <sys/kernel.h>
60 #include <sys/limits.h>
61 #include <sys/lock.h>
62 #include <sys/malloc.h>
63 #include <sys/module.h>
64 #include <sys/mutex.h>
65 #include <sys/proc.h>
66 #include <sys/reboot.h>
67 #include <sys/serial.h>
68 #include <sys/sysctl.h>
69 #include <sys/syslog.h>
70 #include <sys/tty.h>
71 #include <machine/bus.h>
72 #include <sys/rman.h>
73 #include <sys/timepps.h>
74 #include <sys/uio.h>
75 #include <sys/cons.h>
76
77 #include <isa/isavar.h>
78
79 #include <machine/resource.h>
80
81 #include <dev/sio/sioreg.h>
82 #include <dev/sio/siovar.h>
83
84 #ifdef COM_ESP
85 #include <dev/ic/esp.h>
86 #endif
87 #include <dev/ic/ns16550.h>
88
89 #define LOTS_OF_EVENTS  64      /* helps separate urgent events from input */
90
91 #ifdef COM_MULTIPORT
92 /* checks in flags for multiport and which is multiport "master chip"
93  * for a given card
94  */
95 #define COM_ISMULTIPORT(flags)  ((flags) & 0x01)
96 #define COM_MPMASTER(flags)     (((flags) >> 8) & 0x0ff)
97 #define COM_NOTAST4(flags)      ((flags) & 0x04)
98 #else
99 #define COM_ISMULTIPORT(flags)  (0)
100 #endif /* COM_MULTIPORT */
101
102 #define COM_C_IIR_TXRDYBUG      0x80000
103 #define COM_CONSOLE(flags)      ((flags) & 0x10)
104 #define COM_DEBUGGER(flags)     ((flags) & 0x80)
105 #define COM_FIFOSIZE(flags)     (((flags) & 0xff000000) >> 24)
106 #define COM_FORCECONSOLE(flags) ((flags) & 0x20)
107 #define COM_IIR_TXRDYBUG(flags) ((flags) & COM_C_IIR_TXRDYBUG)
108 #define COM_LLCONSOLE(flags)    ((flags) & 0x40)
109 #define COM_LOSESOUTINTS(flags) ((flags) & 0x08)
110 #define COM_NOFIFO(flags)       ((flags) & 0x02)
111 #define COM_NOPROBE(flags)      ((flags) & 0x40000)
112 #define COM_NOSCR(flags)        ((flags) & 0x100000)
113 #define COM_PPSCTS(flags)       ((flags) & 0x10000)
114 #define COM_ST16650A(flags)     ((flags) & 0x20000)
115 #define COM_TI16754(flags)      ((flags) & 0x200000)
116
117 #define sio_getreg(com, off) \
118         (bus_space_read_1((com)->bst, (com)->bsh, (off)))
119 #define sio_setreg(com, off, value) \
120         (bus_space_write_1((com)->bst, (com)->bsh, (off), (value)))
121
122 /*
123  * com state bits.
124  * (CS_BUSY | CS_TTGO) and (CS_BUSY | CS_TTGO | CS_ODEVREADY) must be higher
125  * than the other bits so that they can be tested as a group without masking
126  * off the low bits.
127  *
128  * The following com and tty flags correspond closely:
129  *      CS_BUSY         = TS_BUSY (maintained by comstart(), siopoll() and
130  *                                 comstop())
131  *      CS_TTGO         = ~TS_TTSTOP (maintained by comparam() and comstart())
132  *      CS_CTS_OFLOW    = CCTS_OFLOW (maintained by comparam())
133  *      CS_RTS_IFLOW    = CRTS_IFLOW (maintained by comparam())
134  * TS_FLUSH is not used.
135  * XXX I think TIOCSETA doesn't clear TS_TTSTOP when it clears IXON.
136  * XXX CS_*FLOW should be CF_*FLOW in com->flags (control flags not state).
137  */
138 #define CS_BUSY         0x80    /* output in progress */
139 #define CS_TTGO         0x40    /* output not stopped by XOFF */
140 #define CS_ODEVREADY    0x20    /* external device h/w ready (CTS) */
141 #define CS_CHECKMSR     1       /* check of MSR scheduled */
142 #define CS_CTS_OFLOW    2       /* use CTS output flow control */
143 #define CS_ODONE        4       /* output completed */
144 #define CS_RTS_IFLOW    8       /* use RTS input flow control */
145 #define CSE_BUSYCHECK   1       /* siobusycheck() scheduled */
146
147 static  char const * const      error_desc[] = {
148 #define CE_OVERRUN                      0
149         "silo overflow",
150 #define CE_INTERRUPT_BUF_OVERFLOW       1
151         "interrupt-level buffer overflow",
152 #define CE_TTY_BUF_OVERFLOW             2
153         "tty-level buffer overflow",
154 };
155
156 #define CE_NTYPES                       3
157 #define CE_RECORD(com, errnum)          (++(com)->delta_error_counts[errnum])
158
159 /* types.  XXX - should be elsewhere */
160 typedef u_int   Port_t;         /* hardware port */
161 typedef u_char  bool_t;         /* boolean */
162
163 /* queue of linear buffers */
164 struct lbq {
165         u_char  *l_head;        /* next char to process */
166         u_char  *l_tail;        /* one past the last char to process */
167         struct lbq *l_next;     /* next in queue */
168         bool_t  l_queued;       /* nonzero if queued */
169 };
170
171 /* com device structure */
172 struct com_s {
173         u_char  state;          /* miscellaneous flag bits */
174         u_char  cfcr_image;     /* copy of value written to CFCR */
175 #ifdef COM_ESP
176         bool_t  esp;            /* is this unit a hayes esp board? */
177 #endif
178         u_char  extra_state;    /* more flag bits, separate for order trick */
179         u_char  fifo_image;     /* copy of value written to FIFO */
180         bool_t  hasfifo;        /* nonzero for 16550 UARTs */
181         bool_t  loses_outints;  /* nonzero if device loses output interrupts */
182         u_char  mcr_image;      /* copy of value written to MCR */
183 #ifdef COM_MULTIPORT
184         bool_t  multiport;      /* is this unit part of a multiport device? */
185 #endif /* COM_MULTIPORT */
186         bool_t  no_irq;         /* nonzero if irq is not attached */
187         bool_t  gone;           /* hardware disappeared */
188         bool_t  poll;           /* nonzero if polling is required */
189         bool_t  poll_output;    /* nonzero if polling for output is required */
190         bool_t  st16650a;       /* nonzero if Startech 16650A compatible */
191         int     unit;           /* unit number */
192         u_int   flags;          /* copy of device flags */
193         u_int   tx_fifo_size;
194
195         /*
196          * The high level of the driver never reads status registers directly
197          * because there would be too many side effects to handle conveniently.
198          * Instead, it reads copies of the registers stored here by the
199          * interrupt handler.
200          */
201         u_char  last_modem_status;      /* last MSR read by intr handler */
202         u_char  prev_modem_status;      /* last MSR handled by high level */
203
204         u_char  *ibuf;          /* start of input buffer */
205         u_char  *ibufend;       /* end of input buffer */
206         u_char  *ibufold;       /* old input buffer, to be freed */
207         u_char  *ihighwater;    /* threshold in input buffer */
208         u_char  *iptr;          /* next free spot in input buffer */
209         int     ibufsize;       /* size of ibuf (not include error bytes) */
210         int     ierroff;        /* offset of error bytes in ibuf */
211
212         struct lbq      obufq;  /* head of queue of output buffers */
213         struct lbq      obufs[2];       /* output buffers */
214
215         bus_space_tag_t         bst;
216         bus_space_handle_t      bsh;
217
218         Port_t  data_port;      /* i/o ports */
219 #ifdef COM_ESP
220         Port_t  esp_port;
221 #endif
222         Port_t  int_ctl_port;
223         Port_t  int_id_port;
224         Port_t  modem_ctl_port;
225         Port_t  line_status_port;
226         Port_t  modem_status_port;
227
228         struct tty      *tp;    /* cross reference */
229
230         struct  pps_state pps;
231         int     pps_bit;
232 #ifdef KDB
233         int     alt_brk_state;
234 #endif
235
236         u_long  bytes_in;       /* statistics */
237         u_long  bytes_out;
238         u_int   delta_error_counts[CE_NTYPES];
239         u_long  error_counts[CE_NTYPES];
240
241         u_long  rclk;
242
243         struct resource *irqres;
244         struct resource *ioportres;
245         int     ioportrid;
246         void    *cookie;
247
248         /*
249          * Data area for output buffers.  Someday we should build the output
250          * buffer queue without copying data.
251          */
252         u_char  obuf1[256];
253         u_char  obuf2[256];
254 };
255
256 #ifdef COM_ESP
257 static  int     espattach(struct com_s *com, Port_t esp_port);
258 #endif
259
260 static  void    combreak(struct tty *tp, int sig);
261 static  timeout_t siobusycheck;
262 static  u_int   siodivisor(u_long rclk, speed_t speed);
263 static  void    comclose(struct tty *tp);
264 static  int     comopen(struct tty *tp, struct cdev *dev);
265 static  void    sioinput(struct com_s *com);
266 static  void    siointr1(struct com_s *com);
267 static  int     siointr(void *arg);
268 static  int     commodem(struct tty *tp, int sigon, int sigoff);
269 static  int     comparam(struct tty *tp, struct termios *t);
270 static  void    siopoll(void *);
271 static  void    siosettimeout(void);
272 static  int     siosetwater(struct com_s *com, speed_t speed);
273 static  void    comstart(struct tty *tp);
274 static  void    comstop(struct tty *tp, int rw);
275 static  timeout_t comwakeup;
276
277 char            sio_driver_name[] = "sio";
278 static struct   mtx sio_lock;
279 static int      sio_inited;
280
281 /* table and macro for fast conversion from a unit number to its com struct */
282 devclass_t      sio_devclass;
283 /*
284  * XXX Assmues that devclass_get_device, devclass_get_softc and
285  * device_get_softc are fast interrupt safe.  The current implementation
286  * of these functions are.
287  */
288 #define com_addr(unit)  ((struct com_s *) \
289                          devclass_get_softc(sio_devclass, unit)) /* XXX */
290
291 int     comconsole = -1;
292 static  volatile speed_t        comdefaultrate = CONSPEED;
293 static  u_long                  comdefaultrclk = DEFAULT_RCLK;
294 SYSCTL_ULONG(_machdep, OID_AUTO, conrclk, CTLFLAG_RW, &comdefaultrclk, 0, "");
295 static  speed_t                 gdbdefaultrate = GDBSPEED;
296 SYSCTL_UINT(_machdep, OID_AUTO, gdbspeed, CTLFLAG_RW,
297             &gdbdefaultrate, GDBSPEED, "");
298 static  u_int   com_events;     /* input chars + weighted output completions */
299 static  Port_t  siocniobase;
300 static  int     siocnunit = -1;
301 static  void    *sio_slow_ih;
302 static  void    *sio_fast_ih;
303 static  int     sio_timeout;
304 static  int     sio_timeouts_until_log;
305 static  struct  callout_handle sio_timeout_handle
306     = CALLOUT_HANDLE_INITIALIZER(&sio_timeout_handle);
307 static  int     sio_numunits;
308
309 #ifdef GDB
310 static  Port_t  siogdbiobase = 0;
311 #endif
312
313 #ifdef COM_ESP
314 /* XXX configure this properly. */
315 /* XXX quite broken for new-bus. */
316 static  Port_t  likely_com_ports[] = { 0x3f8, 0x2f8, 0x3e8, 0x2e8, };
317 static  Port_t  likely_esp_ports[] = { 0x140, 0x180, 0x280, 0 };
318 #endif
319
320 /*
321  * handle sysctl read/write requests for console speed
322  * 
323  * In addition to setting comdefaultrate for I/O through /dev/console,
324  * also set the initial and lock values for the /dev/ttyXX device
325  * if there is one associated with the console.  Finally, if the /dev/tty
326  * device has already been open, change the speed on the open running port
327  * itself.
328  */
329
330 static int
331 sysctl_machdep_comdefaultrate(SYSCTL_HANDLER_ARGS)
332 {
333         int error, s;
334         speed_t newspeed;
335         struct com_s *com;
336         struct tty *tp;
337
338         newspeed = comdefaultrate;
339
340         error = sysctl_handle_opaque(oidp, &newspeed, sizeof newspeed, req);
341         if (error || !req->newptr)
342                 return (error);
343
344         comdefaultrate = newspeed;
345
346         if (comconsole < 0)             /* serial console not selected? */
347                 return (0);
348
349         com = com_addr(comconsole);
350         if (com == NULL)
351                 return (ENXIO);
352
353         tp = com->tp;
354         if (tp == NULL)
355                 return (ENXIO);
356
357         /*
358          * set the initial and lock rates for /dev/ttydXX and /dev/cuaXX
359          * (note, the lock rates really are boolean -- if non-zero, disallow
360          *  speed changes)
361          */
362         tp->t_init_in.c_ispeed  = tp->t_init_in.c_ospeed =
363         tp->t_lock_in.c_ispeed  = tp->t_lock_in.c_ospeed =
364         tp->t_init_out.c_ispeed = tp->t_init_out.c_ospeed =
365         tp->t_lock_out.c_ispeed = tp->t_lock_out.c_ospeed = comdefaultrate;
366
367         if (tp->t_state & TS_ISOPEN) {
368                 tp->t_termios.c_ispeed =
369                 tp->t_termios.c_ospeed = comdefaultrate;
370                 s = spltty();
371                 error = comparam(tp, &tp->t_termios);
372                 splx(s);
373         }
374         return error;
375 }
376
377 SYSCTL_PROC(_machdep, OID_AUTO, conspeed, CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_NOFETCH,
378             0, 0, sysctl_machdep_comdefaultrate, "I", "");
379 TUNABLE_INT("machdep.conspeed", __DEVOLATILE(int *, &comdefaultrate));
380
381 #define SET_FLAG(dev, bit) device_set_flags(dev, device_get_flags(dev) | (bit))
382 #define CLR_FLAG(dev, bit) device_set_flags(dev, device_get_flags(dev) & ~(bit))
383
384 /*
385  *      Unload the driver and clear the table.
386  *      XXX this is mostly wrong.
387  *      XXX TODO:
388  *      This is usually called when the card is ejected, but
389  *      can be caused by a kldunload of a controller driver.
390  *      The idea is to reset the driver's view of the device
391  *      and ensure that any driver entry points such as
392  *      read and write do not hang.
393  */
394 int
395 siodetach(device_t dev)
396 {
397         struct com_s    *com;
398
399         com = (struct com_s *) device_get_softc(dev);
400         if (com == NULL) {
401                 device_printf(dev, "NULL com in siounload\n");
402                 return (0);
403         }
404         com->gone = TRUE;
405         if (com->tp)
406                 ttyfree(com->tp);
407         if (com->irqres) {
408                 bus_teardown_intr(dev, com->irqres, com->cookie);
409                 bus_release_resource(dev, SYS_RES_IRQ, 0, com->irqres);
410         }
411         if (com->ioportres)
412                 bus_release_resource(dev, SYS_RES_IOPORT, com->ioportrid,
413                                      com->ioportres);
414         if (com->ibuf != NULL)
415                 free(com->ibuf, M_DEVBUF);
416
417         device_set_softc(dev, NULL);
418         free(com, M_DEVBUF);
419         return (0);
420 }
421
422 int
423 sioprobe(dev, xrid, rclk, noprobe)
424         device_t        dev;
425         int             xrid;
426         u_long          rclk;
427         int             noprobe;
428 {
429 #if 0
430         static bool_t   already_init;
431         device_t        xdev;
432 #endif
433         struct com_s    *com;
434         u_int           divisor;
435         bool_t          failures[10];
436         int             fn;
437         device_t        idev;
438         Port_t          iobase;
439         intrmask_t      irqmap[4];
440         intrmask_t      irqs;
441         u_char          mcr_image;
442         int             result;
443         u_long          xirq;
444         u_int           flags = device_get_flags(dev);
445         int             rid;
446         struct resource *port;
447
448         rid = xrid;
449         port = bus_alloc_resource_anywhere(dev, SYS_RES_IOPORT, &rid,
450                                            IO_COMSIZE, RF_ACTIVE);
451         if (!port)
452                 return (ENXIO);
453
454         com = malloc(sizeof(*com), M_DEVBUF, M_NOWAIT | M_ZERO);
455         if (com == NULL) {
456                 bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
457                 return (ENOMEM);
458         }
459         device_set_softc(dev, com);
460         com->bst = rman_get_bustag(port);
461         com->bsh = rman_get_bushandle(port);
462         if (rclk == 0)
463                 rclk = DEFAULT_RCLK;
464         com->rclk = rclk;
465
466         while (sio_inited != 2)
467                 if (atomic_cmpset_int(&sio_inited, 0, 1)) {
468                         mtx_init(&sio_lock, sio_driver_name, NULL,
469                             (comconsole != -1) ?
470                             MTX_SPIN | MTX_QUIET : MTX_SPIN);
471                         atomic_store_rel_int(&sio_inited, 2);
472                 }
473
474 #if 0
475         /*
476          * XXX this is broken - when we are first called, there are no
477          * previously configured IO ports.  We could hard code
478          * 0x3f8, 0x2f8, 0x3e8, 0x2e8 etc but that's probably worse.
479          * This code has been doing nothing since the conversion since
480          * "count" is zero the first time around.
481          */
482         if (!already_init) {
483                 /*
484                  * Turn off MCR_IENABLE for all likely serial ports.  An unused
485                  * port with its MCR_IENABLE gate open will inhibit interrupts
486                  * from any used port that shares the interrupt vector.
487                  * XXX the gate enable is elsewhere for some multiports.
488                  */
489                 device_t *devs;
490                 int count, i, xioport;
491
492                 devclass_get_devices(sio_devclass, &devs, &count);
493                 for (i = 0; i < count; i++) {
494                         xdev = devs[i];
495                         if (device_is_enabled(xdev) &&
496                             bus_get_resource(xdev, SYS_RES_IOPORT, 0, &xioport,
497                                              NULL) == 0)
498                                 outb(xioport + com_mcr, 0);
499                 }
500                 free(devs, M_TEMP);
501                 already_init = TRUE;
502         }
503 #endif
504
505         if (COM_LLCONSOLE(flags)) {
506                 printf("sio%d: reserved for low-level i/o\n",
507                        device_get_unit(dev));
508                 bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
509                 device_set_softc(dev, NULL);
510                 free(com, M_DEVBUF);
511                 return (ENXIO);
512         }
513
514         /*
515          * If the device is on a multiport card and has an AST/4
516          * compatible interrupt control register, initialize this
517          * register and prepare to leave MCR_IENABLE clear in the mcr.
518          * Otherwise, prepare to set MCR_IENABLE in the mcr.
519          * Point idev to the device struct giving the correct id_irq.
520          * This is the struct for the master device if there is one.
521          */
522         idev = dev;
523         mcr_image = MCR_IENABLE;
524 #ifdef COM_MULTIPORT
525         if (COM_ISMULTIPORT(flags)) {
526                 Port_t xiobase;
527                 u_long io;
528
529                 idev = devclass_get_device(sio_devclass, COM_MPMASTER(flags));
530                 if (idev == NULL) {
531                         printf("sio%d: master device %d not configured\n",
532                                device_get_unit(dev), COM_MPMASTER(flags));
533                         idev = dev;
534                 }
535                 if (!COM_NOTAST4(flags)) {
536                         if (bus_get_resource(idev, SYS_RES_IOPORT, 0, &io,
537                                              NULL) == 0) {
538                                 xiobase = io;
539                                 if (bus_get_resource(idev, SYS_RES_IRQ, 0,
540                                     NULL, NULL) == 0)
541                                         outb(xiobase + com_scr, 0x80);
542                                 else
543                                         outb(xiobase + com_scr, 0);
544                         }
545                         mcr_image = 0;
546                 }
547         }
548 #endif /* COM_MULTIPORT */
549         if (bus_get_resource(idev, SYS_RES_IRQ, 0, NULL, NULL) != 0)
550                 mcr_image = 0;
551
552         bzero(failures, sizeof failures);
553         iobase = rman_get_start(port);
554
555         /*
556          * We don't want to get actual interrupts, just masked ones.
557          * Interrupts from this line should already be masked in the ICU,
558          * but mask them in the processor as well in case there are some
559          * (misconfigured) shared interrupts.
560          */
561         mtx_lock_spin(&sio_lock);
562 /* EXTRA DELAY? */
563
564         /*
565          * For the TI16754 chips, set prescaler to 1 (4 is often the
566          * default after-reset value) as otherwise it's impossible to
567          * get highest baudrates.
568          */
569         if (COM_TI16754(flags)) {
570                 u_char cfcr, efr;
571
572                 cfcr = sio_getreg(com, com_cfcr);
573                 sio_setreg(com, com_cfcr, CFCR_EFR_ENABLE);
574                 efr = sio_getreg(com, com_efr);
575                 /* Unlock extended features to turn off prescaler. */
576                 sio_setreg(com, com_efr, efr | EFR_EFE);
577                 /* Disable EFR. */
578                 sio_setreg(com, com_cfcr, (cfcr != CFCR_EFR_ENABLE) ? cfcr : 0);
579                 /* Turn off prescaler. */
580                 sio_setreg(com, com_mcr,
581                            sio_getreg(com, com_mcr) & ~MCR_PRESCALE);
582                 sio_setreg(com, com_cfcr, CFCR_EFR_ENABLE);
583                 sio_setreg(com, com_efr, efr);
584                 sio_setreg(com, com_cfcr, cfcr);
585         }
586
587         /*
588          * Initialize the speed and the word size and wait long enough to
589          * drain the maximum of 16 bytes of junk in device output queues.
590          * The speed is undefined after a master reset and must be set
591          * before relying on anything related to output.  There may be
592          * junk after a (very fast) soft reboot and (apparently) after
593          * master reset.
594          * XXX what about the UART bug avoided by waiting in comparam()?
595          * We don't want to wait long enough to drain at 2 bps.
596          */
597         if (iobase == siocniobase)
598                 DELAY((16 + 1) * 1000000 / (comdefaultrate / 10));
599         else {
600                 sio_setreg(com, com_cfcr, CFCR_DLAB | CFCR_8BITS);
601                 divisor = siodivisor(rclk, SIO_TEST_SPEED);
602                 sio_setreg(com, com_dlbl, divisor & 0xff);
603                 sio_setreg(com, com_dlbh, divisor >> 8);
604                 sio_setreg(com, com_cfcr, CFCR_8BITS);
605                 DELAY((16 + 1) * 1000000 / (SIO_TEST_SPEED / 10));
606         }
607
608         /*
609          * Enable the interrupt gate and disable device interrupts.  This
610          * should leave the device driving the interrupt line low and
611          * guarantee an edge trigger if an interrupt can be generated.
612          */
613 /* EXTRA DELAY? */
614         sio_setreg(com, com_mcr, mcr_image);
615         sio_setreg(com, com_ier, 0);
616         DELAY(1000);            /* XXX */
617         irqmap[0] = isa_irq_pending();
618
619         /*
620          * Attempt to set loopback mode so that we can send a null byte
621          * without annoying any external device.
622          */
623 /* EXTRA DELAY? */
624         sio_setreg(com, com_mcr, mcr_image | MCR_LOOPBACK);
625
626         /*
627          * Attempt to generate an output interrupt.  On 8250's, setting
628          * IER_ETXRDY generates an interrupt independent of the current
629          * setting and independent of whether the THR is empty.  On 16450's,
630          * setting IER_ETXRDY generates an interrupt independent of the
631          * current setting.  On 16550A's, setting IER_ETXRDY only
632          * generates an interrupt when IER_ETXRDY is not already set.
633          */
634         sio_setreg(com, com_ier, IER_ETXRDY);
635
636         /*
637          * On some 16x50 incompatibles, setting IER_ETXRDY doesn't generate
638          * an interrupt.  They'd better generate one for actually doing
639          * output.  Loopback may be broken on the same incompatibles but
640          * it's unlikely to do more than allow the null byte out.
641          */
642         sio_setreg(com, com_data, 0);
643         if (iobase == siocniobase)
644                 DELAY((1 + 2) * 1000000 / (comdefaultrate / 10));
645         else
646                 DELAY((1 + 2) * 1000000 / (SIO_TEST_SPEED / 10));
647
648         /*
649          * Turn off loopback mode so that the interrupt gate works again
650          * (MCR_IENABLE was hidden).  This should leave the device driving
651          * an interrupt line high.  It doesn't matter if the interrupt
652          * line oscillates while we are not looking at it, since interrupts
653          * are disabled.
654          */
655 /* EXTRA DELAY? */
656         sio_setreg(com, com_mcr, mcr_image);
657  
658         /*
659          * It seems my Xircom CBEM56G Cardbus modem wants to be reset
660          * to 8 bits *again*, or else probe test 0 will fail.
661          * gwk@sgi.com, 4/19/2001
662          */
663         sio_setreg(com, com_cfcr, CFCR_8BITS);
664
665         /*
666          * Some PCMCIA cards (Palido 321s, DC-1S, ...) have the "TXRDY bug",
667          * so we probe for a buggy IIR_TXRDY implementation even in the
668          * noprobe case.  We don't probe for it in the !noprobe case because
669          * noprobe is always set for PCMCIA cards and the problem is not
670          * known to affect any other cards.
671          */
672         if (noprobe) {
673                 /* Read IIR a few times. */
674                 for (fn = 0; fn < 2; fn ++) {
675                         DELAY(10000);
676                         failures[6] = sio_getreg(com, com_iir);
677                 }
678
679                 /* IIR_TXRDY should be clear.  Is it? */
680                 result = 0;
681                 if (failures[6] & IIR_TXRDY) {
682                         /*
683                          * No.  We seem to have the bug.  Does our fix for
684                          * it work?
685                          */
686                         sio_setreg(com, com_ier, 0);
687                         if (sio_getreg(com, com_iir) & IIR_NOPEND) {
688                                 /* Yes.  We discovered the TXRDY bug! */
689                                 SET_FLAG(dev, COM_C_IIR_TXRDYBUG);
690                         } else {
691                                 /* No.  Just fail.  XXX */
692                                 result = ENXIO;
693                                 sio_setreg(com, com_mcr, 0);
694                         }
695                 } else {
696                         /* Yes.  No bug. */
697                         CLR_FLAG(dev, COM_C_IIR_TXRDYBUG);
698                 }
699                 sio_setreg(com, com_ier, 0);
700                 sio_setreg(com, com_cfcr, CFCR_8BITS);
701                 mtx_unlock_spin(&sio_lock);
702                 bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
703                 if (iobase == siocniobase)
704                         result = 0;
705                 /*
706                  * XXX: Since we don't return 0, we shouldn't be relying on
707                  * the softc that we set to persist to the call to attach
708                  * since other probe routines may be called, and the malloc
709                  * here causes subr_bus to not allocate anything for the
710                  * other probes.  Instead, this softc is preserved and other
711                  * probe routines can corrupt it.
712                  */
713                 if (result != 0) {
714                         device_set_softc(dev, NULL);
715                         free(com, M_DEVBUF);
716                 }
717                 return (result == 0 ? BUS_PROBE_DEFAULT + 1 : result);
718         }
719
720         /*
721          * Check that
722          *      o the CFCR, IER and MCR in UART hold the values written to them
723          *        (the values happen to be all distinct - this is good for
724          *        avoiding false positive tests from bus echoes).
725          *      o an output interrupt is generated and its vector is correct.
726          *      o the interrupt goes away when the IIR in the UART is read.
727          */
728 /* EXTRA DELAY? */
729         failures[0] = sio_getreg(com, com_cfcr) - CFCR_8BITS;
730         failures[1] = sio_getreg(com, com_ier) - IER_ETXRDY;
731         failures[2] = sio_getreg(com, com_mcr) - mcr_image;
732         DELAY(10000);           /* Some internal modems need this time */
733         irqmap[1] = isa_irq_pending();
734         failures[4] = (sio_getreg(com, com_iir) & IIR_IMASK) - IIR_TXRDY;
735         DELAY(1000);            /* XXX */
736         irqmap[2] = isa_irq_pending();
737         failures[6] = (sio_getreg(com, com_iir) & IIR_IMASK) - IIR_NOPEND;
738
739         /*
740          * Turn off all device interrupts and check that they go off properly.
741          * Leave MCR_IENABLE alone.  For ports without a master port, it gates
742          * the OUT2 output of the UART to
743          * the ICU input.  Closing the gate would give a floating ICU input
744          * (unless there is another device driving it) and spurious interrupts.
745          * (On the system that this was first tested on, the input floats high
746          * and gives a (masked) interrupt as soon as the gate is closed.)
747          */
748         sio_setreg(com, com_ier, 0);
749         sio_setreg(com, com_cfcr, CFCR_8BITS);  /* dummy to avoid bus echo */
750         failures[7] = sio_getreg(com, com_ier);
751         DELAY(1000);            /* XXX */
752         irqmap[3] = isa_irq_pending();
753         failures[9] = (sio_getreg(com, com_iir) & IIR_IMASK) - IIR_NOPEND;
754
755         mtx_unlock_spin(&sio_lock);
756
757         irqs = irqmap[1] & ~irqmap[0];
758         if (bus_get_resource(idev, SYS_RES_IRQ, 0, &xirq, NULL) == 0 &&
759             ((1 << xirq) & irqs) == 0) {
760                 printf(
761                 "sio%d: configured irq %ld not in bitmap of probed irqs %#x\n",
762                     device_get_unit(dev), xirq, irqs);
763                 printf(
764                 "sio%d: port may not be enabled\n",
765                     device_get_unit(dev));
766         }
767         if (bootverbose)
768                 printf("sio%d: irq maps: %#x %#x %#x %#x\n",
769                     device_get_unit(dev),
770                     irqmap[0], irqmap[1], irqmap[2], irqmap[3]);
771
772         result = 0;
773         for (fn = 0; fn < sizeof failures; ++fn)
774                 if (failures[fn]) {
775                         sio_setreg(com, com_mcr, 0);
776                         result = ENXIO;
777                         if (bootverbose) {
778                                 printf("sio%d: probe failed test(s):",
779                                     device_get_unit(dev));
780                                 for (fn = 0; fn < sizeof failures; ++fn)
781                                         if (failures[fn])
782                                                 printf(" %d", fn);
783                                 printf("\n");
784                         }
785                         break;
786                 }
787         bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
788         if (iobase == siocniobase)
789                 result = 0;
790         /*
791          * XXX: Since we don't return 0, we shouldn't be relying on the softc
792          * that we set to persist to the call to attach since other probe
793          * routines may be called, and the malloc here causes subr_bus to not
794          * allocate anything for the other probes.  Instead, this softc is
795          * preserved and other probe routines can corrupt it.
796          */
797         if (result != 0) {
798                 device_set_softc(dev, NULL);
799                 free(com, M_DEVBUF);
800         }
801         return (result == 0 ? BUS_PROBE_DEFAULT + 1 : result);
802 }
803
804 #ifdef COM_ESP
805 static int
806 espattach(com, esp_port)
807         struct com_s            *com;
808         Port_t                  esp_port;
809 {
810         u_char  dips;
811         u_char  val;
812
813         /*
814          * Check the ESP-specific I/O port to see if we're an ESP
815          * card.  If not, return failure immediately.
816          */
817         if ((inb(esp_port) & 0xf3) == 0) {
818                 printf(" port 0x%x is not an ESP board?\n", esp_port);
819                 return (0);
820         }
821
822         /*
823          * We've got something that claims to be a Hayes ESP card.
824          * Let's hope so.
825          */
826
827         /* Get the dip-switch configuration */
828         outb(esp_port + ESP_CMD1, ESP_GETDIPS);
829         dips = inb(esp_port + ESP_STATUS1);
830
831         /*
832          * Bits 0,1 of dips say which COM port we are.
833          */
834         if (rman_get_start(com->ioportres) == likely_com_ports[dips & 0x03])
835                 printf(" : ESP");
836         else {
837                 printf(" esp_port has com %d\n", dips & 0x03);
838                 return (0);
839         }
840
841         /*
842          * Check for ESP version 2.0 or later:  bits 4,5,6 = 010.
843          */
844         outb(esp_port + ESP_CMD1, ESP_GETTEST);
845         val = inb(esp_port + ESP_STATUS1);      /* clear reg 1 */
846         val = inb(esp_port + ESP_STATUS2);
847         if ((val & 0x70) < 0x20) {
848                 printf("-old (%o)", val & 0x70);
849                 return (0);
850         }
851
852         /*
853          * Check for ability to emulate 16550:  bit 7 == 1
854          */
855         if ((dips & 0x80) == 0) {
856                 printf(" slave");
857                 return (0);
858         }
859
860         /*
861          * Okay, we seem to be a Hayes ESP card.  Whee.
862          */
863         com->esp = TRUE;
864         com->esp_port = esp_port;
865         return (1);
866 }
867 #endif /* COM_ESP */
868
869 int
870 sioattach(dev, xrid, rclk)
871         device_t        dev;
872         int             xrid;
873         u_long          rclk;
874 {
875         struct com_s    *com;
876 #ifdef COM_ESP
877         Port_t          *espp;
878 #endif
879         Port_t          iobase;
880         int             unit;
881         u_int           flags;
882         int             rid;
883         struct resource *port;
884         int             ret;
885         int             error;
886         struct tty      *tp;
887
888         rid = xrid;
889         port = bus_alloc_resource_anywhere(dev, SYS_RES_IOPORT, &rid,
890                                            IO_COMSIZE, RF_ACTIVE);
891         if (!port)
892                 return (ENXIO);
893
894         iobase = rman_get_start(port);
895         unit = device_get_unit(dev);
896         com = device_get_softc(dev);
897         flags = device_get_flags(dev);
898
899         if (unit >= sio_numunits)
900                 sio_numunits = unit + 1;
901         /*
902          * sioprobe() has initialized the device registers as follows:
903          *      o cfcr = CFCR_8BITS.
904          *        It is most important that CFCR_DLAB is off, so that the
905          *        data port is not hidden when we enable interrupts.
906          *      o ier = 0.
907          *        Interrupts are only enabled when the line is open.
908          *      o mcr = MCR_IENABLE, or 0 if the port has AST/4 compatible
909          *        interrupt control register or the config specifies no irq.
910          *        Keeping MCR_DTR and MCR_RTS off might stop the external
911          *        device from sending before we are ready.
912          */
913         bzero(com, sizeof *com);
914         com->unit = unit;
915         com->ioportres = port;
916         com->ioportrid = rid;
917         com->bst = rman_get_bustag(port);
918         com->bsh = rman_get_bushandle(port);
919         com->cfcr_image = CFCR_8BITS;
920         com->loses_outints = COM_LOSESOUTINTS(flags) != 0;
921         com->no_irq = bus_get_resource(dev, SYS_RES_IRQ, 0, NULL, NULL) != 0;
922         com->tx_fifo_size = 1;
923         com->obufs[0].l_head = com->obuf1;
924         com->obufs[1].l_head = com->obuf2;
925
926         com->data_port = iobase + com_data;
927         com->int_ctl_port = iobase + com_ier;
928         com->int_id_port = iobase + com_iir;
929         com->modem_ctl_port = iobase + com_mcr;
930         com->mcr_image = inb(com->modem_ctl_port);
931         com->line_status_port = iobase + com_lsr;
932         com->modem_status_port = iobase + com_msr;
933
934         tp = com->tp = ttyalloc();
935         tp->t_oproc = comstart;
936         tp->t_param = comparam;
937         tp->t_stop = comstop;
938         tp->t_modem = commodem;
939         tp->t_break = combreak;
940         tp->t_close = comclose;
941         tp->t_open = comopen;
942         tp->t_sc = com;
943
944         if (rclk == 0)
945                 rclk = DEFAULT_RCLK;
946         com->rclk = rclk;
947
948         if (unit == comconsole)
949                 ttyconsolemode(tp, comdefaultrate);
950         error = siosetwater(com, tp->t_init_in.c_ispeed);
951         mtx_unlock_spin(&sio_lock);
952         if (error) {
953                 /*
954                  * Leave i/o resources allocated if this is a `cn'-level
955                  * console, so that other devices can't snarf them.
956                  */
957                 if (iobase != siocniobase)
958                         bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
959                 return (ENOMEM);
960         }
961
962         /* attempt to determine UART type */
963         printf("sio%d: type", unit);
964
965         if (!COM_ISMULTIPORT(flags) &&
966             !COM_IIR_TXRDYBUG(flags) && !COM_NOSCR(flags)) {
967                 u_char  scr;
968                 u_char  scr1;
969                 u_char  scr2;
970
971                 scr = sio_getreg(com, com_scr);
972                 sio_setreg(com, com_scr, 0xa5);
973                 scr1 = sio_getreg(com, com_scr);
974                 sio_setreg(com, com_scr, 0x5a);
975                 scr2 = sio_getreg(com, com_scr);
976                 sio_setreg(com, com_scr, scr);
977                 if (scr1 != 0xa5 || scr2 != 0x5a) {
978                         printf(" 8250 or not responding");
979                         goto determined_type;
980                 }
981         }
982         sio_setreg(com, com_fifo, FIFO_ENABLE | FIFO_RX_HIGH);
983         DELAY(100);
984         switch (inb(com->int_id_port) & IIR_FIFO_MASK) {
985         case FIFO_RX_LOW:
986                 printf(" 16450");
987                 break;
988         case FIFO_RX_MEDL:
989                 printf(" 16450?");
990                 break;
991         case FIFO_RX_MEDH:
992                 printf(" 16550?");
993                 break;
994         case FIFO_RX_HIGH:
995                 if (COM_NOFIFO(flags)) {
996                         printf(" 16550A fifo disabled");
997                         break;
998                 }
999                 com->hasfifo = TRUE;
1000                 if (COM_ST16650A(flags)) {
1001                         printf(" ST16650A");
1002                         com->st16650a = TRUE;
1003                         com->tx_fifo_size = 32;
1004                         break;
1005                 }
1006                 if (COM_TI16754(flags)) {
1007                         printf(" TI16754");
1008                         com->tx_fifo_size = 64;
1009                         break;
1010                 }
1011                 printf(" 16550A");
1012 #ifdef COM_ESP
1013                 for (espp = likely_esp_ports; *espp != 0; espp++)
1014                         if (espattach(com, *espp)) {
1015                                 com->tx_fifo_size = 1024;
1016                                 break;
1017                         }
1018                 if (com->esp)
1019                         break;
1020 #endif
1021                 com->tx_fifo_size = COM_FIFOSIZE(flags);
1022                 if (com->tx_fifo_size == 0)
1023                         com->tx_fifo_size = 16;
1024                 else
1025                         printf(" lookalike with %u bytes FIFO",
1026                                com->tx_fifo_size);
1027                 break;
1028         }
1029 #ifdef COM_ESP
1030         if (com->esp) {
1031                 /*
1032                  * Set 16550 compatibility mode.
1033                  * We don't use the ESP_MODE_SCALE bit to increase the
1034                  * fifo trigger levels because we can't handle large
1035                  * bursts of input.
1036                  * XXX flow control should be set in comparam(), not here.
1037                  */
1038                 outb(com->esp_port + ESP_CMD1, ESP_SETMODE);
1039                 outb(com->esp_port + ESP_CMD2, ESP_MODE_RTS | ESP_MODE_FIFO);
1040
1041                 /* Set RTS/CTS flow control. */
1042                 outb(com->esp_port + ESP_CMD1, ESP_SETFLOWTYPE);
1043                 outb(com->esp_port + ESP_CMD2, ESP_FLOW_RTS);
1044                 outb(com->esp_port + ESP_CMD2, ESP_FLOW_CTS);
1045
1046                 /* Set flow-control levels. */
1047                 outb(com->esp_port + ESP_CMD1, ESP_SETRXFLOW);
1048                 outb(com->esp_port + ESP_CMD2, HIBYTE(768));
1049                 outb(com->esp_port + ESP_CMD2, LOBYTE(768));
1050                 outb(com->esp_port + ESP_CMD2, HIBYTE(512));
1051                 outb(com->esp_port + ESP_CMD2, LOBYTE(512));
1052         }
1053 #endif /* COM_ESP */
1054         sio_setreg(com, com_fifo, 0);
1055 determined_type: ;
1056
1057 #ifdef COM_MULTIPORT
1058         if (COM_ISMULTIPORT(flags)) {
1059                 device_t masterdev;
1060
1061                 com->multiport = TRUE;
1062                 printf(" (multiport");
1063                 if (unit == COM_MPMASTER(flags))
1064                         printf(" master");
1065                 printf(")");
1066                 masterdev = devclass_get_device(sio_devclass,
1067                     COM_MPMASTER(flags));
1068                 com->no_irq = (masterdev == NULL || bus_get_resource(masterdev,
1069                     SYS_RES_IRQ, 0, NULL, NULL) != 0);
1070          }
1071 #endif /* COM_MULTIPORT */
1072         if (unit == comconsole)
1073                 printf(", console");
1074         if (COM_IIR_TXRDYBUG(flags))
1075                 printf(" with a buggy IIR_TXRDY implementation");
1076         printf("\n");
1077
1078         if (sio_fast_ih == NULL) {
1079                 swi_add(&tty_intr_event, "sio", siopoll, NULL, SWI_TTY, 0,
1080                     &sio_fast_ih);
1081                 swi_add(&clk_intr_event, "sio", siopoll, NULL, SWI_CLOCK, 0,
1082                     &sio_slow_ih);
1083         }
1084
1085         com->flags = flags;
1086         com->pps.ppscap = PPS_CAPTUREASSERT | PPS_CAPTURECLEAR;
1087         tp->t_pps = &com->pps;
1088
1089         if (COM_PPSCTS(flags))
1090                 com->pps_bit = MSR_CTS;
1091         else
1092                 com->pps_bit = MSR_DCD;
1093         pps_init(&com->pps);
1094
1095         rid = 0;
1096         com->irqres = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_ACTIVE);
1097         if (com->irqres) {
1098                 ret = bus_setup_intr(dev, com->irqres,
1099                                      INTR_TYPE_TTY,
1100                                      siointr, NULL, com, 
1101                                      &com->cookie);
1102                 if (ret) {
1103                         ret = bus_setup_intr(dev,
1104                                              com->irqres, INTR_TYPE_TTY,
1105                                              NULL, (driver_intr_t *)siointr, com, &com->cookie);
1106                         if (ret == 0)
1107                                 device_printf(dev, "unable to activate interrupt in fast mode - using normal mode\n");
1108                 }
1109                 if (ret)
1110                         device_printf(dev, "could not activate interrupt\n");
1111 #if defined(KDB)
1112                 /*
1113                  * Enable interrupts for early break-to-debugger support
1114                  * on the console.
1115                  */
1116                 if (ret == 0 && unit == comconsole)
1117                         outb(siocniobase + com_ier, IER_ERXRDY | IER_ERLS |
1118                             IER_EMSC);
1119 #endif
1120         }
1121
1122         /* We're ready, open the doors... */
1123         ttycreate(tp, TS_CALLOUT, "d%r", unit);
1124
1125         return (0);
1126 }
1127
1128 static int
1129 comopen(struct tty *tp, struct cdev *dev)
1130 {
1131         struct com_s    *com;
1132         int i;
1133
1134         com = tp->t_sc;
1135         com->poll = com->no_irq;
1136         com->poll_output = com->loses_outints;
1137         if (com->hasfifo) {
1138                 /*
1139                  * (Re)enable and drain fifos.
1140                  *
1141                  * Certain SMC chips cause problems if the fifos
1142                  * are enabled while input is ready.  Turn off the
1143                  * fifo if necessary to clear the input.  We test
1144                  * the input ready bit after enabling the fifos
1145                  * since we've already enabled them in comparam()
1146                  * and to handle races between enabling and fresh
1147                  * input.
1148                  */
1149                 for (i = 0; i < 500; i++) {
1150                         sio_setreg(com, com_fifo,
1151                                    FIFO_RCV_RST | FIFO_XMT_RST
1152                                    | com->fifo_image);
1153                         /*
1154                          * XXX the delays are for superstitious
1155                          * historical reasons.  It must be less than
1156                          * the character time at the maximum
1157                          * supported speed (87 usec at 115200 bps
1158                          * 8N1).  Otherwise we might loop endlessly
1159                          * if data is streaming in.  We used to use
1160                          * delays of 100.  That usually worked
1161                          * because DELAY(100) used to usually delay
1162                          * for about 85 usec instead of 100.
1163                          */
1164                         DELAY(50);
1165                         if (!(inb(com->line_status_port) & LSR_RXRDY))
1166                                 break;
1167                         sio_setreg(com, com_fifo, 0);
1168                         DELAY(50);
1169                         (void) inb(com->data_port);
1170                 }
1171                 if (i == 500)
1172                         return (EIO);
1173         }
1174
1175         mtx_lock_spin(&sio_lock);
1176         (void) inb(com->line_status_port);
1177         (void) inb(com->data_port);
1178         com->prev_modem_status = com->last_modem_status
1179             = inb(com->modem_status_port);
1180         outb(com->int_ctl_port,
1181              IER_ERXRDY | IER_ERLS | IER_EMSC
1182              | (COM_IIR_TXRDYBUG(com->flags) ? 0 : IER_ETXRDY));
1183         mtx_unlock_spin(&sio_lock);
1184         siosettimeout();
1185         /* XXX: should be generic ? */
1186         if (com->prev_modem_status & MSR_DCD || ISCALLOUT(dev))
1187                 ttyld_modem(tp, 1);
1188         return (0);
1189 }
1190
1191 static void
1192 comclose(tp)
1193         struct tty      *tp;
1194 {
1195         int             s;
1196         struct com_s    *com;
1197
1198         s = spltty();
1199         com = tp->t_sc;
1200         com->poll = FALSE;
1201         com->poll_output = FALSE;
1202         sio_setreg(com, com_cfcr, com->cfcr_image &= ~CFCR_SBREAK);
1203
1204 #if defined(KDB)
1205         /*
1206          * Leave interrupts enabled and don't clear DTR if this is the
1207          * console. This allows us to detect break-to-debugger events
1208          * while the console device is closed.
1209          */
1210         if (com->unit != comconsole)
1211 #endif
1212         {
1213                 sio_setreg(com, com_ier, 0);
1214                 if (tp->t_cflag & HUPCL
1215                     /*
1216                      * XXX we will miss any carrier drop between here and the
1217                      * next open.  Perhaps we should watch DCD even when the
1218                      * port is closed; it is not sufficient to check it at
1219                      * the next open because it might go up and down while
1220                      * we're not watching.
1221                      */
1222                     || (!tp->t_actout
1223                         && !(com->prev_modem_status & MSR_DCD)
1224                         && !(tp->t_init_in.c_cflag & CLOCAL))
1225                     || !(tp->t_state & TS_ISOPEN)) {
1226                         (void)commodem(tp, 0, SER_DTR);
1227                         ttydtrwaitstart(tp);
1228                 }
1229         }
1230         if (com->hasfifo) {
1231                 /*
1232                  * Disable fifos so that they are off after controlled
1233                  * reboots.  Some BIOSes fail to detect 16550s when the
1234                  * fifos are enabled.
1235                  */
1236                 sio_setreg(com, com_fifo, 0);
1237         }
1238         tp->t_actout = FALSE;
1239         wakeup(&tp->t_actout);
1240         wakeup(TSA_CARR_ON(tp));        /* restart any wopeners */
1241         siosettimeout();
1242         splx(s);
1243 }
1244
1245 static void
1246 siobusycheck(chan)
1247         void    *chan;
1248 {
1249         struct com_s    *com;
1250         int             s;
1251
1252         com = (struct com_s *)chan;
1253
1254         /*
1255          * Clear TS_BUSY if low-level output is complete.
1256          * spl locking is sufficient because siointr1() does not set CS_BUSY.
1257          * If siointr1() clears CS_BUSY after we look at it, then we'll get
1258          * called again.  Reading the line status port outside of siointr1()
1259          * is safe because CS_BUSY is clear so there are no output interrupts
1260          * to lose.
1261          */
1262         s = spltty();
1263         if (com->state & CS_BUSY)
1264                 com->extra_state &= ~CSE_BUSYCHECK;     /* False alarm. */
1265         else if ((inb(com->line_status_port) & (LSR_TSRE | LSR_TXRDY))
1266             == (LSR_TSRE | LSR_TXRDY)) {
1267                 com->tp->t_state &= ~TS_BUSY;
1268                 ttwwakeup(com->tp);
1269                 com->extra_state &= ~CSE_BUSYCHECK;
1270         } else
1271                 timeout(siobusycheck, com, hz / 100);
1272         splx(s);
1273 }
1274
1275 static u_int
1276 siodivisor(rclk, speed)
1277         u_long  rclk;
1278         speed_t speed;
1279 {
1280         long    actual_speed;
1281         u_int   divisor;
1282         int     error;
1283
1284         if (speed == 0)
1285                 return (0);
1286 #if UINT_MAX > (ULONG_MAX - 1) / 8
1287         if (speed > (ULONG_MAX - 1) / 8)
1288                 return (0);
1289 #endif
1290         divisor = (rclk / (8UL * speed) + 1) / 2;
1291         if (divisor == 0 || divisor >= 65536)
1292                 return (0);
1293         actual_speed = rclk / (16UL * divisor);
1294
1295         /* 10 times error in percent: */
1296         error = ((actual_speed - (long)speed) * 2000 / (long)speed + 1) / 2;
1297
1298         /* 3.0% maximum error tolerance: */
1299         if (error < -30 || error > 30)
1300                 return (0);
1301
1302         return (divisor);
1303 }
1304
1305 /*
1306  * Call this function with the sio_lock mutex held.  It will return with the
1307  * lock still held.
1308  */
1309 static void
1310 sioinput(com)
1311         struct com_s    *com;
1312 {
1313         u_char          *buf;
1314         int             incc;
1315         u_char          line_status;
1316         int             recv_data;
1317         struct tty      *tp;
1318
1319         buf = com->ibuf;
1320         tp = com->tp;
1321         if (!(tp->t_state & TS_ISOPEN) || !(tp->t_cflag & CREAD)) {
1322                 com_events -= (com->iptr - com->ibuf);
1323                 com->iptr = com->ibuf;
1324                 return;
1325         }
1326         if (tp->t_state & TS_CAN_BYPASS_L_RINT) {
1327                 /*
1328                  * Avoid the grotesquely inefficient lineswitch routine
1329                  * (ttyinput) in "raw" mode.  It usually takes about 450
1330                  * instructions (that's without canonical processing or echo!).
1331                  * slinput is reasonably fast (usually 40 instructions plus
1332                  * call overhead).
1333                  */
1334                 do {
1335                         /*
1336                          * This may look odd, but it is using save-and-enable
1337                          * semantics instead of the save-and-disable semantics
1338                          * that are used everywhere else.
1339                          */
1340                         mtx_unlock_spin(&sio_lock);
1341                         incc = com->iptr - buf;
1342                         if (tp->t_rawq.c_cc + incc > tp->t_ihiwat
1343                             && (com->state & CS_RTS_IFLOW
1344                                 || tp->t_iflag & IXOFF)
1345                             && !(tp->t_state & TS_TBLOCK))
1346                                 ttyblock(tp);
1347                         com->delta_error_counts[CE_TTY_BUF_OVERFLOW]
1348                                 += b_to_q((char *)buf, incc, &tp->t_rawq);
1349                         buf += incc;
1350                         tk_nin += incc;
1351                         tk_rawcc += incc;
1352                         tp->t_rawcc += incc;
1353                         ttwakeup(tp);
1354                         if (tp->t_state & TS_TTSTOP
1355                             && (tp->t_iflag & IXANY
1356                                 || tp->t_cc[VSTART] == tp->t_cc[VSTOP])) {
1357                                 tp->t_state &= ~TS_TTSTOP;
1358                                 tp->t_lflag &= ~FLUSHO;
1359                                 comstart(tp);
1360                         }
1361                         mtx_lock_spin(&sio_lock);
1362                 } while (buf < com->iptr);
1363         } else {
1364                 do {
1365                         /*
1366                          * This may look odd, but it is using save-and-enable
1367                          * semantics instead of the save-and-disable semantics
1368                          * that are used everywhere else.
1369                          */
1370                         mtx_unlock_spin(&sio_lock);
1371                         line_status = buf[com->ierroff];
1372                         recv_data = *buf++;
1373                         if (line_status
1374                             & (LSR_BI | LSR_FE | LSR_OE | LSR_PE)) {
1375                                 if (line_status & LSR_BI)
1376                                         recv_data |= TTY_BI;
1377                                 if (line_status & LSR_FE)
1378                                         recv_data |= TTY_FE;
1379                                 if (line_status & LSR_OE)
1380                                         recv_data |= TTY_OE;
1381                                 if (line_status & LSR_PE)
1382                                         recv_data |= TTY_PE;
1383                         }
1384                         ttyld_rint(tp, recv_data);
1385                         mtx_lock_spin(&sio_lock);
1386                 } while (buf < com->iptr);
1387         }
1388         com_events -= (com->iptr - com->ibuf);
1389         com->iptr = com->ibuf;
1390
1391         /*
1392          * There is now room for another low-level buffer full of input,
1393          * so enable RTS if it is now disabled and there is room in the
1394          * high-level buffer.
1395          */
1396         if ((com->state & CS_RTS_IFLOW) && !(com->mcr_image & MCR_RTS) &&
1397             !(tp->t_state & TS_TBLOCK))
1398                 outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
1399 }
1400
1401 static int
1402 siointr(arg)
1403         void            *arg;
1404 {
1405         struct com_s    *com;
1406
1407 #ifndef COM_MULTIPORT
1408         com = (struct com_s *)arg;
1409
1410         mtx_lock_spin(&sio_lock);
1411         siointr1(com);
1412         mtx_unlock_spin(&sio_lock);
1413 #else /* COM_MULTIPORT */
1414         bool_t          possibly_more_intrs;
1415         int             unit;
1416
1417         /*
1418          * Loop until there is no activity on any port.  This is necessary
1419          * to get an interrupt edge more than to avoid another interrupt.
1420          * If the IRQ signal is just an OR of the IRQ signals from several
1421          * devices, then the edge from one may be lost because another is
1422          * on.
1423          */
1424         mtx_lock_spin(&sio_lock);
1425         do {
1426                 possibly_more_intrs = FALSE;
1427                 for (unit = 0; unit < sio_numunits; ++unit) {
1428                         com = com_addr(unit);
1429                         /*
1430                          * XXX COM_LOCK();
1431                          * would it work here, or be counter-productive?
1432                          */
1433                         if (com != NULL 
1434                             && !com->gone
1435                             && (inb(com->int_id_port) & IIR_IMASK)
1436                                != IIR_NOPEND) {
1437                                 siointr1(com);
1438                                 possibly_more_intrs = TRUE;
1439                         }
1440                         /* XXX COM_UNLOCK(); */
1441                 }
1442         } while (possibly_more_intrs);
1443         mtx_unlock_spin(&sio_lock);
1444 #endif /* COM_MULTIPORT */
1445         return(FILTER_HANDLED);
1446 }
1447
1448 static struct timespec siots[8];
1449 static int siotso;
1450 static int volatile siotsunit = -1;
1451
1452 static int
1453 sysctl_siots(SYSCTL_HANDLER_ARGS)
1454 {
1455         char buf[128];
1456         long long delta;
1457         size_t len;
1458         int error, i, tso;
1459
1460         for (i = 1, tso = siotso; i < tso; i++) {
1461                 delta = (long long)(siots[i].tv_sec - siots[i - 1].tv_sec) *
1462                     1000000000 +
1463                     (siots[i].tv_nsec - siots[i - 1].tv_nsec);
1464                 len = sprintf(buf, "%lld\n", delta);
1465                 if (delta >= 110000)
1466                         len += sprintf(buf + len - 1, ": *** %ld.%09ld\n",
1467                             (long)siots[i].tv_sec, siots[i].tv_nsec) - 1;
1468                 if (i == tso - 1)
1469                         buf[len - 1] = '\0';
1470                 error = SYSCTL_OUT(req, buf, len);
1471                 if (error != 0)
1472                         return (error);
1473         }
1474         return (0);
1475 }
1476
1477 SYSCTL_PROC(_machdep, OID_AUTO, siots, CTLTYPE_STRING | CTLFLAG_RD,
1478     0, 0, sysctl_siots, "A", "sio timestamps");
1479
1480 static void
1481 siointr1(com)
1482         struct com_s    *com;
1483 {
1484         u_char  int_ctl;
1485         u_char  int_ctl_new;
1486         u_char  line_status;
1487         u_char  modem_status;
1488         u_char  *ioptr;
1489         u_char  recv_data;
1490
1491 #ifdef KDB
1492 again:
1493 #endif
1494
1495         if (COM_IIR_TXRDYBUG(com->flags)) {
1496                 int_ctl = inb(com->int_ctl_port);
1497                 int_ctl_new = int_ctl;
1498         } else {
1499                 int_ctl = 0;
1500                 int_ctl_new = 0;
1501         }
1502
1503         while (!com->gone) {
1504                 if (com->pps.ppsparam.mode & PPS_CAPTUREBOTH) {
1505                         modem_status = inb(com->modem_status_port);
1506                         if ((modem_status ^ com->last_modem_status) &
1507                             com->pps_bit) {
1508                                 pps_capture(&com->pps);
1509                                 pps_event(&com->pps,
1510                                     (modem_status & com->pps_bit) ? 
1511                                     PPS_CAPTUREASSERT : PPS_CAPTURECLEAR);
1512                         }
1513                 }
1514                 line_status = inb(com->line_status_port);
1515
1516                 /* input event? (check first to help avoid overruns) */
1517                 while (line_status & LSR_RCV_MASK) {
1518                         /* break/unnattached error bits or real input? */
1519                         if (!(line_status & LSR_RXRDY))
1520                                 recv_data = 0;
1521                         else
1522                                 recv_data = inb(com->data_port);
1523 #ifdef KDB
1524                         if (com->unit == comconsole &&
1525                             kdb_alt_break(recv_data, &com->alt_brk_state) != 0)
1526                                 goto again;
1527 #endif /* KDB */
1528                         if (line_status & (LSR_BI | LSR_FE | LSR_PE)) {
1529                                 /*
1530                                  * Don't store BI if IGNBRK or FE/PE if IGNPAR.
1531                                  * Otherwise, push the work to a higher level
1532                                  * (to handle PARMRK) if we're bypassing.
1533                                  * Otherwise, convert BI/FE and PE+INPCK to 0.
1534                                  *
1535                                  * This makes bypassing work right in the
1536                                  * usual "raw" case (IGNBRK set, and IGNPAR
1537                                  * and INPCK clear).
1538                                  *
1539                                  * Note: BI together with FE/PE means just BI.
1540                                  */
1541                                 if (line_status & LSR_BI) {
1542 #if defined(KDB)
1543                                         if (com->unit == comconsole) {
1544                                                 kdb_break();
1545                                                 goto cont;
1546                                         }
1547 #endif
1548                                         if (com->tp == NULL
1549                                             || com->tp->t_iflag & IGNBRK)
1550                                                 goto cont;
1551                                 } else {
1552                                         if (com->tp == NULL
1553                                             || com->tp->t_iflag & IGNPAR)
1554                                                 goto cont;
1555                                 }
1556                                 if (com->tp->t_state & TS_CAN_BYPASS_L_RINT
1557                                     && (line_status & (LSR_BI | LSR_FE)
1558                                         || com->tp->t_iflag & INPCK))
1559                                         recv_data = 0;
1560                         }
1561                         ++com->bytes_in;
1562                         if (com->tp != NULL &&
1563                             com->tp->t_hotchar != 0 && recv_data == com->tp->t_hotchar)
1564                                 swi_sched(sio_fast_ih, 0);
1565                         ioptr = com->iptr;
1566                         if (ioptr >= com->ibufend)
1567                                 CE_RECORD(com, CE_INTERRUPT_BUF_OVERFLOW);
1568                         else {
1569                                 if (com->tp != NULL && com->tp->t_do_timestamp)
1570                                         microtime(&com->tp->t_timestamp);
1571                                 ++com_events;
1572                                 swi_sched(sio_slow_ih, SWI_DELAY);
1573 #if 0 /* for testing input latency vs efficiency */
1574 if (com->iptr - com->ibuf == 8)
1575         swi_sched(sio_fast_ih, 0);
1576 #endif
1577                                 ioptr[0] = recv_data;
1578                                 ioptr[com->ierroff] = line_status;
1579                                 com->iptr = ++ioptr;
1580                                 if (ioptr == com->ihighwater
1581                                     && com->state & CS_RTS_IFLOW)
1582                                         outb(com->modem_ctl_port,
1583                                              com->mcr_image &= ~MCR_RTS);
1584                                 if (line_status & LSR_OE)
1585                                         CE_RECORD(com, CE_OVERRUN);
1586                         }
1587 cont:
1588                         if (line_status & LSR_TXRDY
1589                             && com->state >= (CS_BUSY | CS_TTGO | CS_ODEVREADY))
1590                                 goto txrdy;
1591
1592                         /*
1593                          * "& 0x7F" is to avoid the gcc-1.40 generating a slow
1594                          * jump from the top of the loop to here
1595                          */
1596                         line_status = inb(com->line_status_port) & 0x7F;
1597                 }
1598
1599                 /* modem status change? (always check before doing output) */
1600                 modem_status = inb(com->modem_status_port);
1601                 if (modem_status != com->last_modem_status) {
1602                         /*
1603                          * Schedule high level to handle DCD changes.  Note
1604                          * that we don't use the delta bits anywhere.  Some
1605                          * UARTs mess them up, and it's easy to remember the
1606                          * previous bits and calculate the delta.
1607                          */
1608                         com->last_modem_status = modem_status;
1609                         if (!(com->state & CS_CHECKMSR)) {
1610                                 com_events += LOTS_OF_EVENTS;
1611                                 com->state |= CS_CHECKMSR;
1612                                 swi_sched(sio_fast_ih, 0);
1613                         }
1614
1615                         /* handle CTS change immediately for crisp flow ctl */
1616                         if (com->state & CS_CTS_OFLOW) {
1617                                 if (modem_status & MSR_CTS)
1618                                         com->state |= CS_ODEVREADY;
1619                                 else
1620                                         com->state &= ~CS_ODEVREADY;
1621                         }
1622                 }
1623
1624 txrdy:
1625                 /* output queued and everything ready? */
1626                 if (line_status & LSR_TXRDY
1627                     && com->state >= (CS_BUSY | CS_TTGO | CS_ODEVREADY)) {
1628                         ioptr = com->obufq.l_head;
1629                         if (com->tx_fifo_size > 1 && com->unit != siotsunit) {
1630                                 u_int   ocount;
1631
1632                                 ocount = com->obufq.l_tail - ioptr;
1633                                 if (ocount > com->tx_fifo_size)
1634                                         ocount = com->tx_fifo_size;
1635                                 com->bytes_out += ocount;
1636                                 do
1637                                         outb(com->data_port, *ioptr++);
1638                                 while (--ocount != 0);
1639                         } else {
1640                                 outb(com->data_port, *ioptr++);
1641                                 ++com->bytes_out;
1642                                 if (com->unit == siotsunit
1643                                     && siotso < nitems(siots))
1644                                         nanouptime(&siots[siotso++]);
1645                         }
1646                         com->obufq.l_head = ioptr;
1647                         if (COM_IIR_TXRDYBUG(com->flags))
1648                                 int_ctl_new = int_ctl | IER_ETXRDY;
1649                         if (ioptr >= com->obufq.l_tail) {
1650                                 struct lbq      *qp;
1651
1652                                 qp = com->obufq.l_next;
1653                                 qp->l_queued = FALSE;
1654                                 qp = qp->l_next;
1655                                 if (qp != NULL) {
1656                                         com->obufq.l_head = qp->l_head;
1657                                         com->obufq.l_tail = qp->l_tail;
1658                                         com->obufq.l_next = qp;
1659                                 } else {
1660                                         /* output just completed */
1661                                         if (COM_IIR_TXRDYBUG(com->flags))
1662                                                 int_ctl_new = int_ctl
1663                                                               & ~IER_ETXRDY;
1664                                         com->state &= ~CS_BUSY;
1665                                 }
1666                                 if (!(com->state & CS_ODONE)) {
1667                                         com_events += LOTS_OF_EVENTS;
1668                                         com->state |= CS_ODONE;
1669                                         /* handle at high level ASAP */
1670                                         swi_sched(sio_fast_ih, 0);
1671                                 }
1672                         }
1673                         if (COM_IIR_TXRDYBUG(com->flags)
1674                             && int_ctl != int_ctl_new)
1675                                 outb(com->int_ctl_port, int_ctl_new);
1676                 }
1677
1678                 /* finished? */
1679 #ifndef COM_MULTIPORT
1680                 if ((inb(com->int_id_port) & IIR_IMASK) == IIR_NOPEND)
1681 #endif /* COM_MULTIPORT */
1682                         return;
1683         }
1684 }
1685
1686 /* software interrupt handler for SWI_TTY */
1687 static void
1688 siopoll(void *dummy)
1689 {
1690         int             unit;
1691
1692         if (com_events == 0)
1693                 return;
1694 repeat:
1695         for (unit = 0; unit < sio_numunits; ++unit) {
1696                 struct com_s    *com;
1697                 int             incc;
1698                 struct tty      *tp;
1699
1700                 com = com_addr(unit);
1701                 if (com == NULL)
1702                         continue;
1703                 tp = com->tp;
1704                 if (tp == NULL || com->gone) {
1705                         /*
1706                          * Discard any events related to never-opened or
1707                          * going-away devices.
1708                          */
1709                         mtx_lock_spin(&sio_lock);
1710                         incc = com->iptr - com->ibuf;
1711                         com->iptr = com->ibuf;
1712                         if (com->state & CS_CHECKMSR) {
1713                                 incc += LOTS_OF_EVENTS;
1714                                 com->state &= ~CS_CHECKMSR;
1715                         }
1716                         com_events -= incc;
1717                         mtx_unlock_spin(&sio_lock);
1718                         continue;
1719                 }
1720                 if (com->iptr != com->ibuf) {
1721                         mtx_lock_spin(&sio_lock);
1722                         sioinput(com);
1723                         mtx_unlock_spin(&sio_lock);
1724                 }
1725                 if (com->state & CS_CHECKMSR) {
1726                         u_char  delta_modem_status;
1727
1728                         mtx_lock_spin(&sio_lock);
1729                         delta_modem_status = com->last_modem_status
1730                                              ^ com->prev_modem_status;
1731                         com->prev_modem_status = com->last_modem_status;
1732                         com_events -= LOTS_OF_EVENTS;
1733                         com->state &= ~CS_CHECKMSR;
1734                         mtx_unlock_spin(&sio_lock);
1735                         if (delta_modem_status & MSR_DCD)
1736                                 ttyld_modem(tp,
1737                                     com->prev_modem_status & MSR_DCD);
1738                 }
1739                 if (com->state & CS_ODONE) {
1740                         mtx_lock_spin(&sio_lock);
1741                         com_events -= LOTS_OF_EVENTS;
1742                         com->state &= ~CS_ODONE;
1743                         mtx_unlock_spin(&sio_lock);
1744                         if (!(com->state & CS_BUSY)
1745                             && !(com->extra_state & CSE_BUSYCHECK)) {
1746                                 timeout(siobusycheck, com, hz / 100);
1747                                 com->extra_state |= CSE_BUSYCHECK;
1748                         }
1749                         ttyld_start(tp);
1750                 }
1751                 if (com_events == 0)
1752                         break;
1753         }
1754         if (com_events >= LOTS_OF_EVENTS)
1755                 goto repeat;
1756 }
1757
1758 static void
1759 combreak(tp, sig)
1760         struct tty      *tp;
1761         int             sig;
1762 {
1763         struct com_s    *com;
1764
1765         com = tp->t_sc;
1766
1767         if (sig)
1768                 sio_setreg(com, com_cfcr, com->cfcr_image |= CFCR_SBREAK);
1769         else
1770                 sio_setreg(com, com_cfcr, com->cfcr_image &= ~CFCR_SBREAK);
1771 }
1772
1773 static int
1774 comparam(tp, t)
1775         struct tty      *tp;
1776         struct termios  *t;
1777 {
1778         u_int           cfcr;
1779         int             cflag;
1780         struct com_s    *com;
1781         u_int           divisor;
1782         u_char          dlbh;
1783         u_char          dlbl;
1784         u_char          efr_flowbits;
1785         int             s;
1786
1787         com = tp->t_sc;
1788         if (com == NULL)
1789                 return (ENODEV);
1790
1791         /* check requested parameters */
1792         if (t->c_ispeed != (t->c_ospeed != 0 ? t->c_ospeed : tp->t_ospeed))
1793                 return (EINVAL);
1794         divisor = siodivisor(com->rclk, t->c_ispeed);
1795         if (divisor == 0)
1796                 return (EINVAL);
1797
1798         /* parameters are OK, convert them to the com struct and the device */
1799         s = spltty();
1800         if (t->c_ospeed == 0)
1801                 (void)commodem(tp, 0, SER_DTR); /* hang up line */
1802         else
1803                 (void)commodem(tp, SER_DTR, 0);
1804         cflag = t->c_cflag;
1805         switch (cflag & CSIZE) {
1806         case CS5:
1807                 cfcr = CFCR_5BITS;
1808                 break;
1809         case CS6:
1810                 cfcr = CFCR_6BITS;
1811                 break;
1812         case CS7:
1813                 cfcr = CFCR_7BITS;
1814                 break;
1815         default:
1816                 cfcr = CFCR_8BITS;
1817                 break;
1818         }
1819         if (cflag & PARENB) {
1820                 cfcr |= CFCR_PENAB;
1821                 if (!(cflag & PARODD))
1822                         cfcr |= CFCR_PEVEN;
1823         }
1824         if (cflag & CSTOPB)
1825                 cfcr |= CFCR_STOPB;
1826
1827         if (com->hasfifo) {
1828                 /*
1829                  * Use a fifo trigger level low enough so that the input
1830                  * latency from the fifo is less than about 16 msec and
1831                  * the total latency is less than about 30 msec.  These
1832                  * latencies are reasonable for humans.  Serial comms
1833                  * protocols shouldn't expect anything better since modem
1834                  * latencies are larger.
1835                  *
1836                  * The fifo trigger level cannot be set at RX_HIGH for high
1837                  * speed connections without further work on reducing 
1838                  * interrupt disablement times in other parts of the system,
1839                  * without producing silo overflow errors.
1840                  */
1841                 com->fifo_image = com->unit == siotsunit ? 0
1842                                   : t->c_ispeed <= 4800
1843                                   ? FIFO_ENABLE : FIFO_ENABLE | FIFO_RX_MEDH;
1844 #ifdef COM_ESP
1845                 /*
1846                  * The Hayes ESP card needs the fifo DMA mode bit set
1847                  * in compatibility mode.  If not, it will interrupt
1848                  * for each character received.
1849                  */
1850                 if (com->esp)
1851                         com->fifo_image |= FIFO_DMA_MODE;
1852 #endif
1853                 sio_setreg(com, com_fifo, com->fifo_image);
1854         }
1855
1856         /*
1857          * This returns with interrupts disabled so that we can complete
1858          * the speed change atomically.  Keeping interrupts disabled is
1859          * especially important while com_data is hidden.
1860          */
1861         (void) siosetwater(com, t->c_ispeed);
1862
1863         sio_setreg(com, com_cfcr, cfcr | CFCR_DLAB);
1864         /*
1865          * Only set the divisor registers if they would change, since on
1866          * some 16550 incompatibles (UMC8669F), setting them while input
1867          * is arriving loses sync until data stops arriving.
1868          */
1869         dlbl = divisor & 0xFF;
1870         if (sio_getreg(com, com_dlbl) != dlbl)
1871                 sio_setreg(com, com_dlbl, dlbl);
1872         dlbh = divisor >> 8;
1873         if (sio_getreg(com, com_dlbh) != dlbh)
1874                 sio_setreg(com, com_dlbh, dlbh);
1875
1876         efr_flowbits = 0;
1877
1878         if (cflag & CRTS_IFLOW) {
1879                 com->state |= CS_RTS_IFLOW;
1880                 efr_flowbits |= EFR_AUTORTS;
1881                 /*
1882                  * If CS_RTS_IFLOW just changed from off to on, the change
1883                  * needs to be propagated to MCR_RTS.  This isn't urgent,
1884                  * so do it later by calling comstart() instead of repeating
1885                  * a lot of code from comstart() here.
1886                  */
1887         } else if (com->state & CS_RTS_IFLOW) {
1888                 com->state &= ~CS_RTS_IFLOW;
1889                 /*
1890                  * CS_RTS_IFLOW just changed from on to off.  Force MCR_RTS
1891                  * on here, since comstart() won't do it later.
1892                  */
1893                 outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
1894         }
1895
1896         /*
1897          * Set up state to handle output flow control.
1898          * XXX - worth handling MDMBUF (DCD) flow control at the lowest level?
1899          * Now has 10+ msec latency, while CTS flow has 50- usec latency.
1900          */
1901         com->state |= CS_ODEVREADY;
1902         com->state &= ~CS_CTS_OFLOW;
1903         if (cflag & CCTS_OFLOW) {
1904                 com->state |= CS_CTS_OFLOW;
1905                 efr_flowbits |= EFR_AUTOCTS;
1906                 if (!(com->last_modem_status & MSR_CTS))
1907                         com->state &= ~CS_ODEVREADY;
1908         }
1909
1910         if (com->st16650a) {
1911                 sio_setreg(com, com_lcr, LCR_EFR_ENABLE);
1912                 sio_setreg(com, com_efr,
1913                            (sio_getreg(com, com_efr)
1914                             & ~(EFR_AUTOCTS | EFR_AUTORTS)) | efr_flowbits);
1915         }
1916         sio_setreg(com, com_cfcr, com->cfcr_image = cfcr);
1917
1918         /* XXX shouldn't call functions while intrs are disabled. */
1919         ttyldoptim(tp);
1920
1921         mtx_unlock_spin(&sio_lock);
1922         splx(s);
1923         comstart(tp);
1924         if (com->ibufold != NULL) {
1925                 free(com->ibufold, M_DEVBUF);
1926                 com->ibufold = NULL;
1927         }
1928         return (0);
1929 }
1930
1931 /*
1932  * This function must be called with the sio_lock mutex released and will
1933  * return with it obtained.
1934  */
1935 static int
1936 siosetwater(com, speed)
1937         struct com_s    *com;
1938         speed_t         speed;
1939 {
1940         int             cp4ticks;
1941         u_char          *ibuf;
1942         int             ibufsize;
1943         struct tty      *tp;
1944
1945         /*
1946          * Make the buffer size large enough to handle a softtty interrupt
1947          * latency of about 2 ticks without loss of throughput or data
1948          * (about 3 ticks if input flow control is not used or not honoured,
1949          * but a bit less for CS5-CS7 modes).
1950          */
1951         cp4ticks = speed / 10 / hz * 4;
1952         for (ibufsize = 128; ibufsize < cp4ticks;)
1953                 ibufsize <<= 1;
1954         if (ibufsize == com->ibufsize) {
1955                 mtx_lock_spin(&sio_lock);
1956                 return (0);
1957         }
1958
1959         /*
1960          * Allocate input buffer.  The extra factor of 2 in the size is
1961          * to allow for an error byte for each input byte.
1962          */
1963         ibuf = malloc(2 * ibufsize, M_DEVBUF, M_NOWAIT);
1964         if (ibuf == NULL) {
1965                 mtx_lock_spin(&sio_lock);
1966                 return (ENOMEM);
1967         }
1968
1969         /* Initialize non-critical variables. */
1970         com->ibufold = com->ibuf;
1971         com->ibufsize = ibufsize;
1972         tp = com->tp;
1973         if (tp != NULL) {
1974                 tp->t_ififosize = 2 * ibufsize;
1975                 tp->t_ispeedwat = (speed_t)-1;
1976                 tp->t_ospeedwat = (speed_t)-1;
1977         }
1978
1979         /*
1980          * Read current input buffer, if any.  Continue with interrupts
1981          * disabled.
1982          */
1983         mtx_lock_spin(&sio_lock);
1984         if (com->iptr != com->ibuf)
1985                 sioinput(com);
1986
1987         /*-
1988          * Initialize critical variables, including input buffer watermarks.
1989          * The external device is asked to stop sending when the buffer
1990          * exactly reaches high water, or when the high level requests it.
1991          * The high level is notified immediately (rather than at a later
1992          * clock tick) when this watermark is reached.
1993          * The buffer size is chosen so the watermark should almost never
1994          * be reached.
1995          * The low watermark is invisibly 0 since the buffer is always
1996          * emptied all at once.
1997          */
1998         com->iptr = com->ibuf = ibuf;
1999         com->ibufend = ibuf + ibufsize;
2000         com->ierroff = ibufsize;
2001         com->ihighwater = ibuf + 3 * ibufsize / 4;
2002         return (0);
2003 }
2004
2005 static void
2006 comstart(tp)
2007         struct tty      *tp;
2008 {
2009         struct com_s    *com;
2010         int             s;
2011
2012         com = tp->t_sc;
2013         if (com == NULL)
2014                 return;
2015         s = spltty();
2016         mtx_lock_spin(&sio_lock);
2017         if (tp->t_state & TS_TTSTOP)
2018                 com->state &= ~CS_TTGO;
2019         else
2020                 com->state |= CS_TTGO;
2021         if (tp->t_state & TS_TBLOCK) {
2022                 if (com->mcr_image & MCR_RTS && com->state & CS_RTS_IFLOW)
2023                         outb(com->modem_ctl_port, com->mcr_image &= ~MCR_RTS);
2024         } else {
2025                 if (!(com->mcr_image & MCR_RTS) && com->iptr < com->ihighwater
2026                     && com->state & CS_RTS_IFLOW)
2027                         outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
2028         }
2029         mtx_unlock_spin(&sio_lock);
2030         if (tp->t_state & (TS_TIMEOUT | TS_TTSTOP)) {
2031                 ttwwakeup(tp);
2032                 splx(s);
2033                 return;
2034         }
2035         if (tp->t_outq.c_cc != 0) {
2036                 struct lbq      *qp;
2037                 struct lbq      *next;
2038
2039                 if (!com->obufs[0].l_queued) {
2040                         com->obufs[0].l_tail
2041                             = com->obuf1 + q_to_b(&tp->t_outq, com->obuf1,
2042                                                   sizeof com->obuf1);
2043                         com->obufs[0].l_next = NULL;
2044                         com->obufs[0].l_queued = TRUE;
2045                         mtx_lock_spin(&sio_lock);
2046                         if (com->state & CS_BUSY) {
2047                                 qp = com->obufq.l_next;
2048                                 while ((next = qp->l_next) != NULL)
2049                                         qp = next;
2050                                 qp->l_next = &com->obufs[0];
2051                         } else {
2052                                 com->obufq.l_head = com->obufs[0].l_head;
2053                                 com->obufq.l_tail = com->obufs[0].l_tail;
2054                                 com->obufq.l_next = &com->obufs[0];
2055                                 com->state |= CS_BUSY;
2056                         }
2057                         mtx_unlock_spin(&sio_lock);
2058                 }
2059                 if (tp->t_outq.c_cc != 0 && !com->obufs[1].l_queued) {
2060                         com->obufs[1].l_tail
2061                             = com->obuf2 + q_to_b(&tp->t_outq, com->obuf2,
2062                                                   sizeof com->obuf2);
2063                         com->obufs[1].l_next = NULL;
2064                         com->obufs[1].l_queued = TRUE;
2065                         mtx_lock_spin(&sio_lock);
2066                         if (com->state & CS_BUSY) {
2067                                 qp = com->obufq.l_next;
2068                                 while ((next = qp->l_next) != NULL)
2069                                         qp = next;
2070                                 qp->l_next = &com->obufs[1];
2071                         } else {
2072                                 com->obufq.l_head = com->obufs[1].l_head;
2073                                 com->obufq.l_tail = com->obufs[1].l_tail;
2074                                 com->obufq.l_next = &com->obufs[1];
2075                                 com->state |= CS_BUSY;
2076                         }
2077                         mtx_unlock_spin(&sio_lock);
2078                 }
2079                 tp->t_state |= TS_BUSY;
2080         }
2081         mtx_lock_spin(&sio_lock);
2082         if (com->state >= (CS_BUSY | CS_TTGO))
2083                 siointr1(com);  /* fake interrupt to start output */
2084         mtx_unlock_spin(&sio_lock);
2085         ttwwakeup(tp);
2086         splx(s);
2087 }
2088
2089 static void
2090 comstop(tp, rw)
2091         struct tty      *tp;
2092         int             rw;
2093 {
2094         struct com_s    *com;
2095
2096         com = tp->t_sc;
2097         if (com == NULL || com->gone)
2098                 return;
2099         mtx_lock_spin(&sio_lock);
2100         if (rw & FWRITE) {
2101                 if (com->hasfifo)
2102 #ifdef COM_ESP
2103                     /* XXX avoid h/w bug. */
2104                     if (!com->esp)
2105 #endif
2106                         sio_setreg(com, com_fifo,
2107                                    FIFO_XMT_RST | com->fifo_image);
2108                 com->obufs[0].l_queued = FALSE;
2109                 com->obufs[1].l_queued = FALSE;
2110                 if (com->state & CS_ODONE)
2111                         com_events -= LOTS_OF_EVENTS;
2112                 com->state &= ~(CS_ODONE | CS_BUSY);
2113                 com->tp->t_state &= ~TS_BUSY;
2114         }
2115         if (rw & FREAD) {
2116                 if (com->hasfifo)
2117 #ifdef COM_ESP
2118                     /* XXX avoid h/w bug. */
2119                     if (!com->esp)
2120 #endif
2121                         sio_setreg(com, com_fifo,
2122                                    FIFO_RCV_RST | com->fifo_image);
2123                 com_events -= (com->iptr - com->ibuf);
2124                 com->iptr = com->ibuf;
2125         }
2126         mtx_unlock_spin(&sio_lock);
2127         comstart(tp);
2128 }
2129
2130 static int
2131 commodem(struct tty *tp, int sigon, int sigoff)
2132 {
2133         struct com_s    *com;
2134         int     bitand, bitor, msr;
2135
2136         com = tp->t_sc;
2137         if (com->gone)
2138                 return(0);
2139         if (sigon != 0 || sigoff != 0) {
2140                 bitand = bitor = 0;
2141                 if (sigoff & SER_DTR)
2142                         bitand |= MCR_DTR;
2143                 if (sigoff & SER_RTS)
2144                         bitand |= MCR_RTS;
2145                 if (sigon & SER_DTR)
2146                         bitor |= MCR_DTR;
2147                 if (sigon & SER_RTS)
2148                         bitor |= MCR_RTS;
2149                 bitand = ~bitand;
2150                 mtx_lock_spin(&sio_lock);
2151                 com->mcr_image &= bitand;
2152                 com->mcr_image |= bitor;
2153                 outb(com->modem_ctl_port, com->mcr_image);
2154                 mtx_unlock_spin(&sio_lock);
2155                 return (0);
2156         } else {
2157                 bitor = 0;
2158                 if (com->mcr_image & MCR_DTR)
2159                         bitor |= SER_DTR;
2160                 if (com->mcr_image & MCR_RTS)
2161                         bitor |= SER_RTS;
2162                 msr = com->prev_modem_status;
2163                 if (msr & MSR_CTS)
2164                         bitor |= SER_CTS;
2165                 if (msr & MSR_DCD)
2166                         bitor |= SER_DCD;
2167                 if (msr & MSR_DSR)
2168                         bitor |= SER_DSR;
2169                 if (msr & MSR_DSR)
2170                         bitor |= SER_DSR;
2171                 if (msr & (MSR_RI | MSR_TERI))
2172                         bitor |= SER_RI;
2173                 return (bitor);
2174         }
2175 }
2176
2177 static void
2178 siosettimeout()
2179 {
2180         struct com_s    *com;
2181         bool_t          someopen;
2182         int             unit;
2183
2184         /*
2185          * Set our timeout period to 1 second if no polled devices are open.
2186          * Otherwise set it to max(1/200, 1/hz).
2187          * Enable timeouts iff some device is open.
2188          */
2189         untimeout(comwakeup, (void *)NULL, sio_timeout_handle);
2190         sio_timeout = hz;
2191         someopen = FALSE;
2192         for (unit = 0; unit < sio_numunits; ++unit) {
2193                 com = com_addr(unit);
2194                 if (com != NULL && com->tp != NULL
2195                     && com->tp->t_state & TS_ISOPEN && !com->gone) {
2196                         someopen = TRUE;
2197                         if (com->poll || com->poll_output) {
2198                                 sio_timeout = hz > 200 ? hz / 200 : 1;
2199                                 break;
2200                         }
2201                 }
2202         }
2203         if (someopen) {
2204                 sio_timeouts_until_log = hz / sio_timeout;
2205                 sio_timeout_handle = timeout(comwakeup, (void *)NULL,
2206                                              sio_timeout);
2207         } else {
2208                 /* Flush error messages, if any. */
2209                 sio_timeouts_until_log = 1;
2210                 comwakeup((void *)NULL);
2211                 untimeout(comwakeup, (void *)NULL, sio_timeout_handle);
2212         }
2213 }
2214
2215 static void
2216 comwakeup(chan)
2217         void    *chan;
2218 {
2219         struct com_s    *com;
2220         int             unit;
2221
2222         sio_timeout_handle = timeout(comwakeup, (void *)NULL, sio_timeout);
2223
2224         /*
2225          * Recover from lost output interrupts.
2226          * Poll any lines that don't use interrupts.
2227          */
2228         for (unit = 0; unit < sio_numunits; ++unit) {
2229                 com = com_addr(unit);
2230                 if (com != NULL && !com->gone
2231                     && (com->state >= (CS_BUSY | CS_TTGO) || com->poll)) {
2232                         mtx_lock_spin(&sio_lock);
2233                         siointr1(com);
2234                         mtx_unlock_spin(&sio_lock);
2235                 }
2236         }
2237
2238         /*
2239          * Check for and log errors, but not too often.
2240          */
2241         if (--sio_timeouts_until_log > 0)
2242                 return;
2243         sio_timeouts_until_log = hz / sio_timeout;
2244         for (unit = 0; unit < sio_numunits; ++unit) {
2245                 int     errnum;
2246
2247                 com = com_addr(unit);
2248                 if (com == NULL)
2249                         continue;
2250                 if (com->gone)
2251                         continue;
2252                 for (errnum = 0; errnum < CE_NTYPES; ++errnum) {
2253                         u_int   delta;
2254                         u_long  total;
2255
2256                         mtx_lock_spin(&sio_lock);
2257                         delta = com->delta_error_counts[errnum];
2258                         com->delta_error_counts[errnum] = 0;
2259                         mtx_unlock_spin(&sio_lock);
2260                         if (delta == 0)
2261                                 continue;
2262                         total = com->error_counts[errnum] += delta;
2263                         log(LOG_ERR, "sio%d: %u more %s%s (total %lu)\n",
2264                             unit, delta, error_desc[errnum],
2265                             delta == 1 ? "" : "s", total);
2266                 }
2267         }
2268 }
2269
2270 /*
2271  * Following are all routines needed for SIO to act as console
2272  */
2273 struct siocnstate {
2274         u_char  dlbl;
2275         u_char  dlbh;
2276         u_char  ier;
2277         u_char  cfcr;
2278         u_char  mcr;
2279 };
2280
2281 /*
2282  * This is a function in order to not replicate "ttyd%d" more
2283  * places than absolutely necessary.
2284  */
2285 static void
2286 siocnset(struct consdev *cd, int unit)
2287 {
2288
2289         cd->cn_unit = unit;
2290         sprintf(cd->cn_name, "ttyd%d", unit);
2291 }
2292
2293 static speed_t siocngetspeed(Port_t, u_long rclk);
2294 static void siocnclose(struct siocnstate *sp, Port_t iobase);
2295 static void siocnopen(struct siocnstate *sp, Port_t iobase, int speed);
2296 static void siocntxwait(Port_t iobase);
2297
2298 static cn_probe_t sio_cnprobe;
2299 static cn_init_t sio_cninit;
2300 static cn_term_t sio_cnterm;
2301 static cn_getc_t sio_cngetc;
2302 static cn_putc_t sio_cnputc;
2303 static cn_grab_t sio_cngrab;
2304 static cn_ungrab_t sio_cnungrab;
2305
2306 CONSOLE_DRIVER(sio);
2307
2308 static void
2309 siocntxwait(iobase)
2310         Port_t  iobase;
2311 {
2312         int     timo;
2313
2314         /*
2315          * Wait for any pending transmission to finish.  Required to avoid
2316          * the UART lockup bug when the speed is changed, and for normal
2317          * transmits.
2318          */
2319         timo = 100000;
2320         while ((inb(iobase + com_lsr) & (LSR_TSRE | LSR_TXRDY))
2321                != (LSR_TSRE | LSR_TXRDY) && --timo != 0)
2322                 ;
2323 }
2324
2325 /*
2326  * Read the serial port specified and try to figure out what speed
2327  * it's currently running at.  We're assuming the serial port has
2328  * been initialized and is basically idle.  This routine is only intended
2329  * to be run at system startup.
2330  *
2331  * If the value read from the serial port doesn't make sense, return 0.
2332  */
2333
2334 static speed_t
2335 siocngetspeed(iobase, rclk)
2336         Port_t  iobase;
2337         u_long  rclk;
2338 {
2339         u_int   divisor;
2340         u_char  dlbh;
2341         u_char  dlbl;
2342         u_char  cfcr;
2343
2344         cfcr = inb(iobase + com_cfcr);
2345         outb(iobase + com_cfcr, CFCR_DLAB | cfcr);
2346
2347         dlbl = inb(iobase + com_dlbl);
2348         dlbh = inb(iobase + com_dlbh);
2349
2350         outb(iobase + com_cfcr, cfcr);
2351
2352         divisor = dlbh << 8 | dlbl;
2353
2354         /* XXX there should be more sanity checking. */
2355         if (divisor == 0)
2356                 return (CONSPEED);
2357         return (rclk / (16UL * divisor));
2358 }
2359
2360 static void
2361 siocnopen(sp, iobase, speed)
2362         struct siocnstate       *sp;
2363         Port_t                  iobase;
2364         int                     speed;
2365 {
2366         u_int   divisor;
2367         u_char  dlbh;
2368         u_char  dlbl;
2369
2370         /*
2371          * Save all the device control registers except the fifo register
2372          * and set our default ones (cs8 -parenb speed=comdefaultrate).
2373          * We can't save the fifo register since it is read-only.
2374          */
2375         sp->ier = inb(iobase + com_ier);
2376         outb(iobase + com_ier, 0);      /* spltty() doesn't stop siointr() */
2377         siocntxwait(iobase);
2378         sp->cfcr = inb(iobase + com_cfcr);
2379         outb(iobase + com_cfcr, CFCR_DLAB | CFCR_8BITS);
2380         sp->dlbl = inb(iobase + com_dlbl);
2381         sp->dlbh = inb(iobase + com_dlbh);
2382         /*
2383          * Only set the divisor registers if they would change, since on
2384          * some 16550 incompatibles (Startech), setting them clears the
2385          * data input register.  This also reduces the effects of the
2386          * UMC8669F bug.
2387          */
2388         divisor = siodivisor(comdefaultrclk, speed);
2389         dlbl = divisor & 0xFF;
2390         if (sp->dlbl != dlbl)
2391                 outb(iobase + com_dlbl, dlbl);
2392         dlbh = divisor >> 8;
2393         if (sp->dlbh != dlbh)
2394                 outb(iobase + com_dlbh, dlbh);
2395         outb(iobase + com_cfcr, CFCR_8BITS);
2396         sp->mcr = inb(iobase + com_mcr);
2397         /*
2398          * We don't want interrupts, but must be careful not to "disable"
2399          * them by clearing the MCR_IENABLE bit, since that might cause
2400          * an interrupt by floating the IRQ line.
2401          */
2402         outb(iobase + com_mcr, (sp->mcr & MCR_IENABLE) | MCR_DTR | MCR_RTS);
2403 }
2404
2405 static void
2406 siocnclose(sp, iobase)
2407         struct siocnstate       *sp;
2408         Port_t                  iobase;
2409 {
2410         /*
2411          * Restore the device control registers.
2412          */
2413         siocntxwait(iobase);
2414         outb(iobase + com_cfcr, CFCR_DLAB | CFCR_8BITS);
2415         if (sp->dlbl != inb(iobase + com_dlbl))
2416                 outb(iobase + com_dlbl, sp->dlbl);
2417         if (sp->dlbh != inb(iobase + com_dlbh))
2418                 outb(iobase + com_dlbh, sp->dlbh);
2419         outb(iobase + com_cfcr, sp->cfcr);
2420         /*
2421          * XXX damp oscillations of MCR_DTR and MCR_RTS by not restoring them.
2422          */
2423         outb(iobase + com_mcr, sp->mcr | MCR_DTR | MCR_RTS);
2424         outb(iobase + com_ier, sp->ier);
2425 }
2426
2427 static void
2428 sio_cnprobe(cp)
2429         struct consdev  *cp;
2430 {
2431         speed_t                 boot_speed;
2432         u_char                  cfcr;
2433         u_int                   divisor;
2434         int                     s, unit;
2435         struct siocnstate       sp;
2436
2437         /*
2438          * Find our first enabled console, if any.  If it is a high-level
2439          * console device, then initialize it and return successfully.
2440          * If it is a low-level console device, then initialize it and
2441          * return unsuccessfully.  It must be initialized in both cases
2442          * for early use by console drivers and debuggers.  Initializing
2443          * the hardware is not necessary in all cases, since the i/o
2444          * routines initialize it on the fly, but it is necessary if
2445          * input might arrive while the hardware is switched back to an
2446          * uninitialized state.  We can't handle multiple console devices
2447          * yet because our low-level routines don't take a device arg.
2448          * We trust the user to set the console flags properly so that we
2449          * don't need to probe.
2450          */
2451         cp->cn_pri = CN_DEAD;
2452
2453         for (unit = 0; unit < 16; unit++) { /* XXX need to know how many */
2454                 int flags;
2455
2456                 if (resource_disabled("sio", unit))
2457                         continue;
2458                 if (resource_int_value("sio", unit, "flags", &flags))
2459                         continue;
2460                 if (COM_CONSOLE(flags) || COM_DEBUGGER(flags)) {
2461                         int port;
2462                         Port_t iobase;
2463
2464                         if (resource_int_value("sio", unit, "port", &port))
2465                                 continue;
2466                         iobase = port;
2467                         s = spltty();
2468                         if ((boothowto & RB_SERIAL) && COM_CONSOLE(flags)) {
2469                                 boot_speed =
2470                                     siocngetspeed(iobase, comdefaultrclk);
2471                                 if (boot_speed)
2472                                         comdefaultrate = boot_speed;
2473                         }
2474
2475                         /*
2476                          * Initialize the divisor latch.  We can't rely on
2477                          * siocnopen() to do this the first time, since it 
2478                          * avoids writing to the latch if the latch appears
2479                          * to have the correct value.  Also, if we didn't
2480                          * just read the speed from the hardware, then we
2481                          * need to set the speed in hardware so that
2482                          * switching it later is null.
2483                          */
2484                         cfcr = inb(iobase + com_cfcr);
2485                         outb(iobase + com_cfcr, CFCR_DLAB | cfcr);
2486                         divisor = siodivisor(comdefaultrclk, comdefaultrate);
2487                         outb(iobase + com_dlbl, divisor & 0xff);
2488                         outb(iobase + com_dlbh, divisor >> 8);
2489                         outb(iobase + com_cfcr, cfcr);
2490
2491                         siocnopen(&sp, iobase, comdefaultrate);
2492
2493                         splx(s);
2494                         if (COM_CONSOLE(flags) && !COM_LLCONSOLE(flags)) {
2495                                 siocnset(cp, unit);
2496                                 cp->cn_pri = COM_FORCECONSOLE(flags)
2497                                              || boothowto & RB_SERIAL
2498                                              ? CN_REMOTE : CN_NORMAL;
2499                                 siocniobase = iobase;
2500                                 siocnunit = unit;
2501                         }
2502 #ifdef GDB
2503                         if (COM_DEBUGGER(flags))
2504                                 siogdbiobase = iobase;
2505 #endif
2506                 }
2507         }
2508 }
2509
2510 static void
2511 sio_cninit(cp)
2512         struct consdev  *cp;
2513 {
2514         comconsole = cp->cn_unit;
2515 }
2516
2517 static void
2518 sio_cnterm(cp)
2519         struct consdev  *cp;
2520 {
2521         comconsole = -1;
2522 }
2523
2524 static void
2525 sio_cngrab(struct consdev *cp)
2526 {
2527 }
2528
2529 static void
2530 sio_cnungrab(struct consdev *cp)
2531 {
2532 }
2533
2534 static int
2535 sio_cngetc(struct consdev *cd)
2536 {
2537         int     c;
2538         Port_t  iobase;
2539         int     s;
2540         struct siocnstate       sp;
2541         speed_t speed;
2542
2543         if (cd != NULL && cd->cn_unit == siocnunit) {
2544                 iobase = siocniobase;
2545                 speed = comdefaultrate;
2546         } else {
2547 #ifdef GDB
2548                 iobase = siogdbiobase;
2549                 speed = gdbdefaultrate;
2550 #else
2551                 return (-1);
2552 #endif
2553         }
2554         s = spltty();
2555         siocnopen(&sp, iobase, speed);
2556         if (inb(iobase + com_lsr) & LSR_RXRDY)
2557                 c = inb(iobase + com_data);
2558         else
2559                 c = -1;
2560         siocnclose(&sp, iobase);
2561         splx(s);
2562         return (c);
2563 }
2564
2565 static void
2566 sio_cnputc(struct consdev *cd, int c)
2567 {
2568         int     need_unlock;
2569         int     s;
2570         struct siocnstate       sp;
2571         Port_t  iobase;
2572         speed_t speed;
2573
2574         if (cd != NULL && cd->cn_unit == siocnunit) {
2575                 iobase = siocniobase;
2576                 speed = comdefaultrate;
2577         } else {
2578 #ifdef GDB
2579                 iobase = siogdbiobase;
2580                 speed = gdbdefaultrate;
2581 #else
2582                 return;
2583 #endif
2584         }
2585         s = spltty();
2586         need_unlock = 0;
2587         if (!kdb_active && sio_inited == 2 && !mtx_owned(&sio_lock)) {
2588                 mtx_lock_spin(&sio_lock);
2589                 need_unlock = 1;
2590         }
2591         siocnopen(&sp, iobase, speed);
2592         siocntxwait(iobase);
2593         outb(iobase + com_data, c);
2594         siocnclose(&sp, iobase);
2595         if (need_unlock)
2596                 mtx_unlock_spin(&sio_lock);
2597         splx(s);
2598 }
2599
2600 /*
2601  * Remote gdb(1) support.
2602  */
2603
2604 #if defined(GDB)
2605
2606 #include <gdb/gdb.h>
2607
2608 static gdb_probe_f siogdbprobe;
2609 static gdb_init_f siogdbinit;
2610 static gdb_term_f siogdbterm;
2611 static gdb_getc_f siogdbgetc;
2612 static gdb_putc_f siogdbputc;
2613
2614 GDB_DBGPORT(sio, siogdbprobe, siogdbinit, siogdbterm, siogdbgetc, siogdbputc);
2615
2616 static int
2617 siogdbprobe(void)
2618 {
2619         return ((siogdbiobase != 0) ? 0 : -1);
2620 }
2621
2622 static void
2623 siogdbinit(void)
2624 {
2625 }
2626
2627 static void
2628 siogdbterm(void)
2629 {
2630 }
2631
2632 static void
2633 siogdbputc(int c)
2634 {
2635         sio_cnputc(NULL, c);
2636 }
2637
2638 static int
2639 siogdbgetc(void)
2640 {
2641         return (sio_cngetc(NULL));
2642 }
2643
2644 #endif