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