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