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