]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/pc98/cbus/sio.c
merge fix for boot-time hang on centos' xen
[FreeBSD/FreeBSD.git] / sys / pc98 / cbus / sio.c
1 /*-
2  * Copyright (c) 1991 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * $FreeBSD$
30  *      from: @(#)com.c 7.5 (Berkeley) 5/16/91
31  *      from: i386/isa sio.c,v 1.234
32  */
33
34 #include "opt_comconsole.h"
35 #include "opt_compat.h"
36 #include "opt_gdb.h"
37 #include "opt_kdb.h"
38 #include "opt_sio.h"
39
40 /*
41  * Serial driver, based on 386BSD-0.1 com driver.
42  * Mostly rewritten to use pseudo-DMA.
43  * Works for National Semiconductor NS8250-NS16550AF UARTs.
44  * COM driver, based on HP dca driver.
45  *
46  * Changes for PC-Card integration:
47  *      - Added PC-Card driver table and handlers
48  */
49 /*===============================================================
50  * 386BSD(98),FreeBSD-1.1x(98) com driver.
51  * -----
52  * modified for PC9801 by M.Ishii 
53  *                      Kyoto University Microcomputer Club (KMC)
54  * Chou "TEFUTEFU" Hirotomi
55  *                      Kyoto Univ.  the faculty of medicine
56  *===============================================================
57  * FreeBSD-2.0.1(98) sio driver.
58  * -----
59  * modified for pc98 Internal i8251 and MICRO CORE MC16550II
60  *                      T.Koike(hfc01340@niftyserve.or.jp)
61  * implement kernel device configuration
62  *                      aizu@orient.center.nitech.ac.jp
63  *
64  * Notes.
65  * -----
66  *  PC98 localization based on 386BSD(98) com driver. Using its PC98 local
67  *  functions.
68  *  This driver is under debugging,has bugs.
69  */
70 /*
71  * modified for AIWA B98-01
72  * by T.Hatanou <hatanou@yasuda.comm.waseda.ac.jp>  last update: 15 Sep.1995 
73  */
74 /*
75  * Modified by Y.Takahashi of Kogakuin University.
76  */
77 /*
78  * modified for 8251(FIFO) by Seigo TANIMURA <tanimura@FreeBSD.org>
79  */
80
81 #include <sys/param.h>
82 #include <sys/systm.h>
83 #include <sys/bus.h>
84 #include <sys/conf.h>
85 #include <sys/fcntl.h>
86 #include <sys/interrupt.h>
87 #include <sys/kdb.h>
88 #include <sys/kernel.h>
89 #include <sys/limits.h>
90 #include <sys/lock.h>
91 #include <sys/malloc.h>
92 #include <sys/module.h>
93 #include <sys/mutex.h>
94 #include <sys/proc.h>
95 #include <sys/reboot.h>
96 #include <sys/serial.h>
97 #include <sys/sysctl.h>
98 #include <sys/syslog.h>
99 #include <sys/tty.h>
100 #include <machine/bus.h>
101 #include <sys/rman.h>
102 #include <sys/timepps.h>
103 #include <sys/uio.h>
104 #include <sys/cons.h>
105
106 #include <isa/isavar.h>
107
108 #include <machine/resource.h>
109
110 #include <dev/sio/sioreg.h>
111 #include <dev/sio/siovar.h>
112
113 #ifdef PC98
114 #include <pc98/cbus/cbus.h>
115 #include <pc98/pc98/pc98_machdep.h>
116 #endif
117
118 #ifdef COM_ESP
119 #include <dev/ic/esp.h>
120 #endif
121 #include <dev/ic/ns16550.h>
122 #ifdef PC98
123 #include <dev/ic/i8251.h>
124 #include <dev/ic/rsa.h>
125 #endif
126
127 #define LOTS_OF_EVENTS  64      /* helps separate urgent events from input */
128
129 /*
130  * Meaning of flags:
131  *
132  * 0x00000001   shared IRQs
133  * 0x00000002   disable FIFO
134  * 0x00000008   recover sooner from lost output interrupts
135  * 0x00000010   device is potential system console
136  * 0x00000020   device is forced to become system console
137  * 0x00000040   device is reserved for low-level IO
138  * 0x00000080   use this port for remote kernel debugging
139  * 0x0000??00   minor number of master port
140  * 0x00010000   PPS timestamping on CTS instead of DCD
141  * 0x00080000   IIR_TXRDY bug
142  * 0x00400000   If no comconsole found then mark as a comconsole
143  * 0x1?000000   interface type
144  */
145
146 #ifdef COM_MULTIPORT
147 /* checks in flags for multiport and which is multiport "master chip"
148  * for a given card
149  */
150 #define COM_ISMULTIPORT(flags)  ((flags) & 0x01)
151 #define COM_MPMASTER(flags)     (((flags) >> 8) & 0x0ff)
152 #ifndef PC98
153 #define COM_NOTAST4(flags)      ((flags) & 0x04)
154 #endif
155 #else
156 #define COM_ISMULTIPORT(flags)  (0)
157 #endif /* COM_MULTIPORT */
158
159 #define COM_C_IIR_TXRDYBUG      0x80000
160 #define COM_CONSOLE(flags)      ((flags) & 0x10)
161 #define COM_DEBUGGER(flags)     ((flags) & 0x80)
162 #ifndef PC98
163 #define COM_FIFOSIZE(flags)     (((flags) & 0xff000000) >> 24)
164 #endif
165 #define COM_FORCECONSOLE(flags) ((flags) & 0x20)
166 #define COM_IIR_TXRDYBUG(flags) ((flags) & COM_C_IIR_TXRDYBUG)
167 #define COM_LLCONSOLE(flags)    ((flags) & 0x40)
168 #define COM_LOSESOUTINTS(flags) ((flags) & 0x08)
169 #define COM_NOFIFO(flags)       ((flags) & 0x02)
170 #ifndef PC98
171 #define COM_NOSCR(flags)        ((flags) & 0x100000)
172 #endif
173 #define COM_PPSCTS(flags)       ((flags) & 0x10000)
174 #ifndef PC98
175 #define COM_ST16650A(flags)     ((flags) & 0x20000)
176 #define COM_TI16754(flags)      ((flags) & 0x200000)
177 #endif
178
179 #define sio_getreg(com, off) \
180         (bus_space_read_1((com)->bst, (com)->bsh, (off)))
181 #define sio_setreg(com, off, value) \
182         (bus_space_write_1((com)->bst, (com)->bsh, (off), (value)))
183
184 /*
185  * com state bits.
186  * (CS_BUSY | CS_TTGO) and (CS_BUSY | CS_TTGO | CS_ODEVREADY) must be higher
187  * than the other bits so that they can be tested as a group without masking
188  * off the low bits.
189  *
190  * The following com and tty flags correspond closely:
191  *      CS_BUSY         = TS_BUSY (maintained by comstart(), siopoll() and
192  *                                 comstop())
193  *      CS_TTGO         = ~TS_TTSTOP (maintained by comparam() and comstart())
194  *      CS_CTS_OFLOW    = CCTS_OFLOW (maintained by comparam())
195  *      CS_RTS_IFLOW    = CRTS_IFLOW (maintained by comparam())
196  * TS_FLUSH is not used.
197  * XXX I think TIOCSETA doesn't clear TS_TTSTOP when it clears IXON.
198  * XXX CS_*FLOW should be CF_*FLOW in com->flags (control flags not state).
199  */
200 #define CS_BUSY         0x80    /* output in progress */
201 #define CS_TTGO         0x40    /* output not stopped by XOFF */
202 #define CS_ODEVREADY    0x20    /* external device h/w ready (CTS) */
203 #define CS_CHECKMSR     1       /* check of MSR scheduled */
204 #define CS_CTS_OFLOW    2       /* use CTS output flow control */
205 #define CS_ODONE        4       /* output completed */
206 #define CS_RTS_IFLOW    8       /* use RTS input flow control */
207 #define CSE_BUSYCHECK   1       /* siobusycheck() scheduled */
208
209 static  char const * const      error_desc[] = {
210 #define CE_OVERRUN                      0
211         "silo overflow",
212 #define CE_INTERRUPT_BUF_OVERFLOW       1
213         "interrupt-level buffer overflow",
214 #define CE_TTY_BUF_OVERFLOW             2
215         "tty-level buffer overflow",
216 };
217
218 #define CE_NTYPES                       3
219 #define CE_RECORD(com, errnum)          (++(com)->delta_error_counts[errnum])
220
221 /* types.  XXX - should be elsewhere */
222 typedef u_int   Port_t;         /* hardware port */
223 typedef u_char  bool_t;         /* boolean */
224
225 /* queue of linear buffers */
226 struct lbq {
227         u_char  *l_head;        /* next char to process */
228         u_char  *l_tail;        /* one past the last char to process */
229         struct lbq *l_next;     /* next in queue */
230         bool_t  l_queued;       /* nonzero if queued */
231 };
232
233 /* com device structure */
234 struct com_s {
235         u_char  state;          /* miscellaneous flag bits */
236         u_char  cfcr_image;     /* copy of value written to CFCR */
237 #ifdef COM_ESP
238         bool_t  esp;            /* is this unit a hayes esp board? */
239 #endif
240         u_char  extra_state;    /* more flag bits, separate for order trick */
241         u_char  fifo_image;     /* copy of value written to FIFO */
242         bool_t  hasfifo;        /* nonzero for 16550 UARTs */
243         bool_t  loses_outints;  /* nonzero if device loses output interrupts */
244         u_char  mcr_image;      /* copy of value written to MCR */
245 #ifdef COM_MULTIPORT
246         bool_t  multiport;      /* is this unit part of a multiport device? */
247 #endif /* COM_MULTIPORT */
248         bool_t  no_irq;         /* nonzero if irq is not attached */
249         bool_t  gone;           /* hardware disappeared */
250         bool_t  poll;           /* nonzero if polling is required */
251         bool_t  poll_output;    /* nonzero if polling for output is required */
252         bool_t  st16650a;       /* nonzero if Startech 16650A compatible */
253         int     unit;           /* unit number */
254         u_int   flags;          /* copy of device flags */
255         u_int   tx_fifo_size;
256
257         /*
258          * The high level of the driver never reads status registers directly
259          * because there would be too many side effects to handle conveniently.
260          * Instead, it reads copies of the registers stored here by the
261          * interrupt handler.
262          */
263         u_char  last_modem_status;      /* last MSR read by intr handler */
264         u_char  prev_modem_status;      /* last MSR handled by high level */
265
266         u_char  *ibuf;          /* start of input buffer */
267         u_char  *ibufend;       /* end of input buffer */
268         u_char  *ibufold;       /* old input buffer, to be freed */
269         u_char  *ihighwater;    /* threshold in input buffer */
270         u_char  *iptr;          /* next free spot in input buffer */
271         int     ibufsize;       /* size of ibuf (not include error bytes) */
272         int     ierroff;        /* offset of error bytes in ibuf */
273
274         struct lbq      obufq;  /* head of queue of output buffers */
275         struct lbq      obufs[2];       /* output buffers */
276
277         bus_space_tag_t         bst;
278         bus_space_handle_t      bsh;
279
280 #ifdef PC98
281         Port_t  cmd_port;
282         Port_t  sts_port;
283         Port_t  in_modem_port;
284         Port_t  intr_ctrl_port;
285         Port_t  rsabase;        /* Iobase address of an I/O-DATA RSA board. */
286         int     intr_enable;
287         int     pc98_prev_modem_status;
288         int     pc98_modem_delta;
289         int     modem_car_chg_timer;
290         int     pc98_prev_siocmd;
291         int     pc98_prev_siomod;
292         int     modem_checking;
293         int     pc98_if_type;
294
295         bool_t  pc98_8251fifo;
296         bool_t  pc98_8251fifo_enable;
297 #endif /* PC98 */
298         Port_t  data_port;      /* i/o ports */
299 #ifdef COM_ESP
300         Port_t  esp_port;
301 #endif
302         Port_t  int_ctl_port;
303         Port_t  int_id_port;
304         Port_t  modem_ctl_port;
305         Port_t  line_status_port;
306         Port_t  modem_status_port;
307
308         struct tty      *tp;    /* cross reference */
309
310         struct  pps_state pps;
311         int     pps_bit;
312 #ifdef ALT_BREAK_TO_DEBUGGER
313         int     alt_brk_state;
314 #endif
315
316         u_long  bytes_in;       /* statistics */
317         u_long  bytes_out;
318         u_int   delta_error_counts[CE_NTYPES];
319         u_long  error_counts[CE_NTYPES];
320
321         u_long  rclk;
322
323         struct resource *irqres;
324         struct resource *ioportres;
325         int     ioportrid;
326         void    *cookie;
327
328         /*
329          * Data area for output buffers.  Someday we should build the output
330          * buffer queue without copying data.
331          */
332 #ifdef PC98
333         int     obufsize;
334         u_char  *obuf1;
335         u_char  *obuf2;
336 #else
337         u_char  obuf1[256];
338         u_char  obuf2[256];
339 #endif
340 };
341
342 #ifdef COM_ESP
343 static  int     espattach(struct com_s *com, Port_t esp_port);
344 #endif
345
346 static  void    combreak(struct tty *tp, int sig);
347 static  timeout_t siobusycheck;
348 static  u_int   siodivisor(u_long rclk, speed_t speed);
349 static  void    comclose(struct tty *tp);
350 static  int     comopen(struct tty *tp, struct cdev *dev);
351 static  void    sioinput(struct com_s *com);
352 static  void    siointr1(struct com_s *com);
353 static  void    siointr(void *arg);
354 static  int     commodem(struct tty *tp, int sigon, int sigoff);
355 static  int     comparam(struct tty *tp, struct termios *t);
356 static  void    siopoll(void *);
357 static  void    siosettimeout(void);
358 static  int     siosetwater(struct com_s *com, speed_t speed);
359 static  void    comstart(struct tty *tp);
360 static  void    comstop(struct tty *tp, int rw);
361 static  timeout_t comwakeup;
362
363 char            sio_driver_name[] = "sio";
364 static struct   mtx sio_lock;
365 static int      sio_inited;
366
367 /* table and macro for fast conversion from a unit number to its com struct */
368 devclass_t      sio_devclass;
369 #define com_addr(unit)  ((struct com_s *) \
370                          devclass_get_softc(sio_devclass, unit)) /* XXX */
371
372 int     comconsole = -1;
373 static  volatile speed_t        comdefaultrate = CONSPEED;
374 static  u_long                  comdefaultrclk = DEFAULT_RCLK;
375 SYSCTL_ULONG(_machdep, OID_AUTO, conrclk, CTLFLAG_RW, &comdefaultrclk, 0, "");
376 static  speed_t                 gdbdefaultrate = GDBSPEED;
377 SYSCTL_UINT(_machdep, OID_AUTO, gdbspeed, CTLFLAG_RW,
378             &gdbdefaultrate, GDBSPEED, "");
379 static  u_int   com_events;     /* input chars + weighted output completions */
380 static  Port_t  siocniobase;
381 static  int     siocnunit = -1;
382 static  void    *sio_slow_ih;
383 static  void    *sio_fast_ih;
384 static  int     sio_timeout;
385 static  int     sio_timeouts_until_log;
386 static  struct  callout_handle sio_timeout_handle
387     = CALLOUT_HANDLE_INITIALIZER(&sio_timeout_handle);
388 static  int     sio_numunits;
389
390 #ifdef PC98
391 struct  siodev  {
392         short   if_type;
393         short   irq;
394         Port_t  cmd, sts, ctrl, mod;
395 };
396 static  int     sysclock;
397
398 #define COM_INT_DISABLE         {int previpri; previpri=spltty();
399 #define COM_INT_ENABLE          splx(previpri);}
400 #define IEN_TxFLAG              IEN_Tx
401
402 #define COM_CARRIER_DETECT_EMULATE      0
403 #define PC98_CHECK_MODEM_INTERVAL       (hz/10)
404 #define DCD_OFF_TOLERANCE               2
405 #define DCD_ON_RECOGNITION              2
406 #define IS_8251(if_type)                (!(if_type & 0x10))
407 #define COM1_EXT_CLOCK                  0x40000
408
409 static  void    commint(struct cdev *dev);
410 static  void    com_tiocm_bis(struct com_s *com, int msr);
411 static  void    com_tiocm_bic(struct com_s *com, int msr);
412 static  int     com_tiocm_get(struct com_s *com);
413 static  int     com_tiocm_get_delta(struct com_s *com);
414 static  void    pc98_msrint_start(struct cdev *dev);
415 static  void    com_cflag_and_speed_set(struct com_s *com, int cflag, int speed);
416 static  int     pc98_ttspeedtab(struct com_s *com, int speed, u_int *divisor);
417 static  int     pc98_get_modem_status(struct com_s *com);
418 static  timeout_t       pc98_check_msr;
419 static  void    pc98_set_baud_rate(struct com_s *com, u_int count);
420 static  void    pc98_i8251_reset(struct com_s *com, int mode, int command);
421 static  void    pc98_disable_i8251_interrupt(struct com_s *com, int mod);
422 static  void    pc98_enable_i8251_interrupt(struct com_s *com, int mod);
423 static  int     pc98_check_i8251_interrupt(struct com_s *com);
424 static  int     pc98_i8251_get_cmd(struct com_s *com);
425 static  int     pc98_i8251_get_mod(struct com_s *com);
426 static  void    pc98_i8251_set_cmd(struct com_s *com, int x);
427 static  void    pc98_i8251_or_cmd(struct com_s *com, int x);
428 static  void    pc98_i8251_clear_cmd(struct com_s *com, int x);
429 static  void    pc98_i8251_clear_or_cmd(struct com_s *com, int clr, int x);
430 static  int     pc98_check_if_type(device_t dev, struct siodev *iod);
431 static  int     pc98_check_8251vfast(void);
432 static  int     pc98_check_8251fifo(void);
433 static  void    pc98_check_sysclock(void);
434 static  void    pc98_set_ioport(struct com_s *com);
435
436 #define com_int_Tx_disable(com) \
437                 pc98_disable_i8251_interrupt(com,IEN_Tx|IEN_TxEMP)
438 #define com_int_Tx_enable(com) \
439                 pc98_enable_i8251_interrupt(com,IEN_TxFLAG)
440 #define com_int_Rx_disable(com) \
441                 pc98_disable_i8251_interrupt(com,IEN_Rx)
442 #define com_int_Rx_enable(com) \
443                 pc98_enable_i8251_interrupt(com,IEN_Rx)
444 #define com_int_TxRx_disable(com) \
445                 pc98_disable_i8251_interrupt(com,IEN_Tx|IEN_TxEMP|IEN_Rx)
446 #define com_int_TxRx_enable(com) \
447                 pc98_enable_i8251_interrupt(com,IEN_TxFLAG|IEN_Rx)
448 #define com_send_break_on(com) \
449                 (IS_8251((com)->pc98_if_type) ? \
450                  pc98_i8251_or_cmd((com), CMD8251_SBRK) : \
451                  sio_setreg((com), com_cfcr, (com)->cfcr_image |= CFCR_SBREAK))
452 #define com_send_break_off(com) \
453                 (IS_8251((com)->pc98_if_type) ? \
454                  pc98_i8251_clear_cmd((com), CMD8251_SBRK) : \
455                  sio_setreg((com), com_cfcr, (com)->cfcr_image &= ~CFCR_SBREAK))
456
457 static struct speedtab pc98speedtab[] = {       /* internal RS232C interface */
458         { 0,            0, },
459         { 50,           50, },
460         { 75,           75, },
461         { 150,          150, },
462         { 200,          200, },
463         { 300,          300, },
464         { 600,          600, },
465         { 1200,         1200, },
466         { 2400,         2400, },
467         { 4800,         4800, },
468         { 9600,         9600, },
469         { 19200,        19200, },
470         { 38400,        38400, },
471         { 51200,        51200, },
472         { 76800,        76800, },
473         { 20800,        20800, },
474         { 31200,        31200, },
475         { 41600,        41600, },
476         { 62400,        62400, },
477         { -1,           -1 }
478 };
479 static struct speedtab pc98fast_speedtab[] = {
480         { 9600,         0x80 | (DEFAULT_RCLK / (16 * (9600))), },
481         { 19200,        0x80 | (DEFAULT_RCLK / (16 * (19200))), },
482         { 38400,        0x80 | (DEFAULT_RCLK / (16 * (38400))), },
483         { 57600,        0x80 | (DEFAULT_RCLK / (16 * (57600))), },
484         { 115200,       0x80 | (DEFAULT_RCLK / (16 * (115200))), },
485         { -1,           -1 }
486 };
487 static struct speedtab comspeedtab_pio9032b[] = {
488         { 300,          6, },
489         { 600,          5, },
490         { 1200,         4, },
491         { 2400,         3, },
492         { 4800,         2, },
493         { 9600,         1, },
494         { 19200,        0, },
495         { 38400,        7, },
496         { -1,           -1 }
497 };
498 static struct speedtab comspeedtab_b98_01[] = {
499         { 75,           11, },
500         { 150,          10, },
501         { 300,          9, },
502         { 600,          8, },
503         { 1200,         7, },
504         { 2400,         6, },
505         { 4800,         5, },
506         { 9600,         4, },
507         { 19200,        3, },
508         { 38400,        2, },
509         { 76800,        1, },
510         { 153600,       0, },
511         { -1,           -1 }
512 };
513 static struct speedtab comspeedtab_ind[] = {
514         { 300,          1536, },
515         { 600,          768, },
516         { 1200,         384, },
517         { 2400,         192, },
518         { 4800,         96, },
519         { 9600,         48, },
520         { 19200,        24, },
521         { 38400,        12, },
522         { 57600,        8, },
523         { 115200,       4, },
524         { 153600,       3, },
525         { 230400,       2, },
526         { 460800,       1, },
527         { -1,           -1 }
528 };
529
530 struct {
531         char    *name;
532         short   port_table[7];
533         short   irr_mask;
534         struct speedtab *speedtab;
535         short   check_irq;
536 } if_8251_type[] = {
537         /* COM_IF_INTERNAL */
538         { " (internal)", {0x30, 0x32, 0x32, 0x33, 0x35, -1, -1},
539              -1, pc98speedtab, 1 },
540         /* COM_IF_PC9861K_1 */
541         { " (PC9861K)", {0xb1, 0xb3, 0xb3, 0xb0, 0xb0, -1, -1},
542              3, NULL, 1 },
543         /* COM_IF_PC9861K_2 */
544         { " (PC9861K)", {0xb9, 0xbb, 0xbb, 0xb2, 0xb2, -1, -1},
545               3, NULL, 1 },
546         /* COM_IF_IND_SS_1 */
547         { " (IND-SS)", {0xb1, 0xb3, 0xb3, 0xb0, 0xb0, 0xb3, -1},
548              3, comspeedtab_ind, 1 },
549         /* COM_IF_IND_SS_2 */
550         { " (IND-SS)", {0xb9, 0xbb, 0xbb, 0xb2, 0xb2, 0xbb, -1},
551              3, comspeedtab_ind, 1 },
552         /* COM_IF_PIO9032B_1 */
553         { " (PIO9032B)", {0xb1, 0xb3, 0xb3, 0xb0, 0xb0, 0xb8, -1},
554               7, comspeedtab_pio9032b, 1 },
555         /* COM_IF_PIO9032B_2 */
556         { " (PIO9032B)", {0xb9, 0xbb, 0xbb, 0xb2, 0xb2, 0xba, -1},
557               7, comspeedtab_pio9032b, 1 },
558         /* COM_IF_B98_01_1 */
559         { " (B98-01)", {0xb1, 0xb3, 0xb3, 0xb0, 0xb0, 0xd1, 0xd3},
560               7, comspeedtab_b98_01, 0 },
561         /* COM_IF_B98_01_2 */
562         { " (B98-01)", {0xb9, 0xbb, 0xbb, 0xb2, 0xb2, 0xd5, 0xd7},
563              7, comspeedtab_b98_01, 0 },
564 };
565 #define PC98SIO_data_port(type)         (if_8251_type[type].port_table[0])
566 #define PC98SIO_cmd_port(type)          (if_8251_type[type].port_table[1])
567 #define PC98SIO_sts_port(type)          (if_8251_type[type].port_table[2])
568 #define PC98SIO_in_modem_port(type)     (if_8251_type[type].port_table[3])
569 #define PC98SIO_intr_ctrl_port(type)    (if_8251_type[type].port_table[4])
570 #define PC98SIO_baud_rate_port(type)    (if_8251_type[type].port_table[5])
571 #define PC98SIO_func_port(type)         (if_8251_type[type].port_table[6])
572
573 #define I8251F_data             0x130
574 #define I8251F_lsr              0x132
575 #define I8251F_msr              0x134
576 #define I8251F_iir              0x136
577 #define I8251F_fcr              0x138
578 #define I8251F_div              0x13a
579
580
581 static bus_addr_t port_table_0[] =
582         {0x000, 0x001, 0x002, 0x003, 0x004, 0x005, 0x006, 0x007};
583 static bus_addr_t port_table_1[] =
584         {0x000, 0x002, 0x004, 0x006, 0x008, 0x00a, 0x00c, 0x00e};
585 static bus_addr_t port_table_8[] =
586         {0x000, 0x100, 0x200, 0x300, 0x400, 0x500, 0x600, 0x700};
587 static bus_addr_t port_table_rsa[] = {
588         0x008, 0x009, 0x00a, 0x00b, 0x00c, 0x00d, 0x00e, 0x00f,
589         0x000, 0x001, 0x002, 0x003, 0x004, 0x005, 0x006, 0x007
590 };
591
592 struct {
593         char            *name;
594         short           irr_read;
595         short           irr_write;
596         bus_addr_t      *iat;
597         bus_size_t      iatsz;
598         u_long          rclk;
599 } if_16550a_type[] = {
600         /* COM_IF_RSA98 */
601         {" (RSA-98)", -1, -1, port_table_0, IO_COMSIZE, DEFAULT_RCLK},
602         /* COM_IF_NS16550 */
603         {"", -1, -1, port_table_0, IO_COMSIZE, DEFAULT_RCLK},
604         /* COM_IF_SECOND_CCU */
605         {"", -1, -1, port_table_0, IO_COMSIZE, DEFAULT_RCLK},
606         /* COM_IF_MC16550II */
607         {" (MC16550II)", -1, 0x1000, port_table_8, IO_COMSIZE,
608          DEFAULT_RCLK * 4},
609         /* COM_IF_MCRS98 */
610         {" (MC-RS98)", -1, 0x1000, port_table_8, IO_COMSIZE, DEFAULT_RCLK * 4},
611         /* COM_IF_RSB3000 */
612         {" (RSB-3000)", 0xbf, -1, port_table_1, IO_COMSIZE, DEFAULT_RCLK * 10},
613         /* COM_IF_RSB384 */
614         {" (RSB-384)", 0xbf, -1, port_table_1, IO_COMSIZE, DEFAULT_RCLK * 10},
615         /* COM_IF_MODEM_CARD */
616         {"", -1, -1, port_table_0, IO_COMSIZE, DEFAULT_RCLK},
617         /* COM_IF_RSA98III */
618         {" (RSA-98III)", -1, -1, port_table_rsa, 16, DEFAULT_RCLK * 8},
619         /* COM_IF_ESP98 */
620         {" (ESP98)", -1, -1, port_table_1, IO_COMSIZE, DEFAULT_RCLK * 4},
621 };
622 #endif /* PC98 */
623
624 #ifdef GDB
625 static  Port_t  siogdbiobase = 0;
626 #endif
627
628 #ifdef COM_ESP
629 #ifdef PC98
630
631 /* XXX configure this properly. */
632 /* XXX quite broken for new-bus. */
633 static  Port_t  likely_com_ports[] = { 0, 0xb0, 0xb1, 0 };
634 static  Port_t  likely_esp_ports[] = { 0xc0d0, 0 };
635
636 #define ESP98_CMD1      (ESP_CMD1 * 0x100)
637 #define ESP98_CMD2      (ESP_CMD2 * 0x100)
638 #define ESP98_STATUS1   (ESP_STATUS1 * 0x100)
639 #define ESP98_STATUS2   (ESP_STATUS2 * 0x100)
640
641 #else /* PC98 */
642
643 /* XXX configure this properly. */
644 static  Port_t  likely_com_ports[] = { 0x3f8, 0x2f8, 0x3e8, 0x2e8, };
645 static  Port_t  likely_esp_ports[] = { 0x140, 0x180, 0x280, 0 };
646
647 #endif /* PC98 */
648 #endif
649
650 /*
651  * handle sysctl read/write requests for console speed
652  * 
653  * In addition to setting comdefaultrate for I/O through /dev/console,
654  * also set the initial and lock values for the /dev/ttyXX device
655  * if there is one associated with the console.  Finally, if the /dev/tty
656  * device has already been open, change the speed on the open running port
657  * itself.
658  */
659
660 static int
661 sysctl_machdep_comdefaultrate(SYSCTL_HANDLER_ARGS)
662 {
663         int error, s;
664         speed_t newspeed;
665         struct com_s *com;
666         struct tty *tp;
667
668         newspeed = comdefaultrate;
669
670         error = sysctl_handle_opaque(oidp, &newspeed, sizeof newspeed, req);
671         if (error || !req->newptr)
672                 return (error);
673
674         comdefaultrate = newspeed;
675
676         if (comconsole < 0)             /* serial console not selected? */
677                 return (0);
678
679         com = com_addr(comconsole);
680         if (com == NULL)
681                 return (ENXIO);
682
683         tp = com->tp;
684         if (tp == NULL)
685                 return (ENXIO);
686
687         /*
688          * set the initial and lock rates for /dev/ttydXX and /dev/cuaXX
689          * (note, the lock rates really are boolean -- if non-zero, disallow
690          *  speed changes)
691          */
692         tp->t_init_in.c_ispeed  = tp->t_init_in.c_ospeed =
693         tp->t_lock_in.c_ispeed  = tp->t_lock_in.c_ospeed =
694         tp->t_init_out.c_ispeed = tp->t_init_out.c_ospeed =
695         tp->t_lock_out.c_ispeed = tp->t_lock_out.c_ospeed = comdefaultrate;
696
697         if (tp->t_state & TS_ISOPEN) {
698                 tp->t_termios.c_ispeed =
699                 tp->t_termios.c_ospeed = comdefaultrate;
700                 s = spltty();
701                 error = comparam(tp, &tp->t_termios);
702                 splx(s);
703         }
704         return error;
705 }
706
707 SYSCTL_PROC(_machdep, OID_AUTO, conspeed, CTLTYPE_INT | CTLFLAG_RW,
708             0, 0, sysctl_machdep_comdefaultrate, "I", "");
709
710 /*
711  *      Unload the driver and clear the table.
712  *      XXX this is mostly wrong.
713  *      XXX TODO:
714  *      This is usually called when the card is ejected, but
715  *      can be caused by a kldunload of a controller driver.
716  *      The idea is to reset the driver's view of the device
717  *      and ensure that any driver entry points such as
718  *      read and write do not hang.
719  */
720 int
721 siodetach(device_t dev)
722 {
723         struct com_s    *com;
724
725         com = (struct com_s *) device_get_softc(dev);
726         if (com == NULL) {
727                 device_printf(dev, "NULL com in siounload\n");
728                 return (0);
729         }
730         com->gone = TRUE;
731         if (com->tp)
732                 ttyfree(com->tp);
733         if (com->irqres) {
734                 bus_teardown_intr(dev, com->irqres, com->cookie);
735                 bus_release_resource(dev, SYS_RES_IRQ, 0, com->irqres);
736         }
737         if (com->ioportres)
738                 bus_release_resource(dev, SYS_RES_IOPORT, com->ioportrid,
739                                      com->ioportres);
740         if (com->ibuf != NULL)
741                 free(com->ibuf, M_DEVBUF);
742 #ifdef PC98
743         if (com->obuf1 != NULL)
744                 free(com->obuf1, M_DEVBUF);
745 #endif
746
747         device_set_softc(dev, NULL);
748         free(com, M_DEVBUF);
749         return (0);
750 }
751
752 int
753 sioprobe(dev, xrid, rclk, noprobe)
754         device_t        dev;
755         int             xrid;
756         u_long          rclk;
757         int             noprobe;
758 {
759 #if 0
760         static bool_t   already_init;
761         device_t        xdev;
762 #endif
763         struct com_s    *com;
764         u_int           divisor;
765         bool_t          failures[10];
766         int             fn;
767         device_t        idev;
768         Port_t          iobase;
769         intrmask_t      irqmap[4];
770         intrmask_t      irqs;
771         u_char          mcr_image;
772         int             result;
773         u_long          xirq;
774         u_int           flags = device_get_flags(dev);
775         int             rid;
776         struct resource *port;
777 #ifdef PC98
778         int             tmp;
779         struct siodev   iod;
780 #endif
781
782 #ifdef PC98
783         iod.if_type = GET_IFTYPE(flags);
784         if ((iod.if_type < 0 || iod.if_type > COM_IF_END1) &&
785             (iod.if_type < 0x10 || iod.if_type > COM_IF_END2))
786                         return ENXIO;
787 #endif
788
789         rid = xrid;
790 #ifdef PC98
791         if (IS_8251(iod.if_type)) {
792                 port = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid,
793                                               RF_ACTIVE);
794         } else if (iod.if_type == COM_IF_MODEM_CARD ||
795                    iod.if_type == COM_IF_RSA98III ||
796                    isa_get_vendorid(dev)) {
797                 port = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid, 0, ~0,
798                   if_16550a_type[iod.if_type & 0x0f].iatsz, RF_ACTIVE);
799         } else {
800                 port = isa_alloc_resourcev(dev, SYS_RES_IOPORT, &rid,
801                    if_16550a_type[iod.if_type & 0x0f].iat,
802                    if_16550a_type[iod.if_type & 0x0f].iatsz, RF_ACTIVE);
803         }
804 #else
805         port = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid,
806                                   0, ~0, IO_COMSIZE, RF_ACTIVE);
807 #endif
808         if (!port)
809                 return (ENXIO);
810 #ifdef PC98
811         if (!IS_8251(iod.if_type)) {
812                 if (isa_load_resourcev(port,
813                        if_16550a_type[iod.if_type & 0x0f].iat,
814                        if_16550a_type[iod.if_type & 0x0f].iatsz) != 0) {
815                         bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
816                         return ENXIO;
817                 }
818         }
819 #endif
820
821         com = malloc(sizeof(*com), M_DEVBUF, M_NOWAIT | M_ZERO);
822         if (com == NULL) {
823                 bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
824                 return (ENOMEM);
825         }
826         device_set_softc(dev, com);
827         com->bst = rman_get_bustag(port);
828         com->bsh = rman_get_bushandle(port);
829 #ifdef PC98
830         if (!IS_8251(iod.if_type) && rclk == 0)
831                 rclk = if_16550a_type[iod.if_type & 0x0f].rclk;
832 #else
833         if (rclk == 0)
834                 rclk = DEFAULT_RCLK;
835 #endif
836         com->rclk = rclk;
837
838         while (sio_inited != 2)
839                 if (atomic_cmpset_int(&sio_inited, 0, 1)) {
840                         mtx_init(&sio_lock, sio_driver_name, NULL,
841                             (comconsole != -1) ?
842                             MTX_SPIN | MTX_QUIET : MTX_SPIN);
843                         atomic_store_rel_int(&sio_inited, 2);
844                 }
845
846 #if 0
847         /*
848          * XXX this is broken - when we are first called, there are no
849          * previously configured IO ports.  We could hard code
850          * 0x3f8, 0x2f8, 0x3e8, 0x2e8 etc but that's probably worse.
851          * This code has been doing nothing since the conversion since
852          * "count" is zero the first time around.
853          */
854         if (!already_init) {
855                 /*
856                  * Turn off MCR_IENABLE for all likely serial ports.  An unused
857                  * port with its MCR_IENABLE gate open will inhibit interrupts
858                  * from any used port that shares the interrupt vector.
859                  * XXX the gate enable is elsewhere for some multiports.
860                  */
861                 device_t *devs;
862                 int count, i, xioport;
863 #ifdef PC98
864                 int xiftype;
865 #endif
866
867                 devclass_get_devices(sio_devclass, &devs, &count);
868 #ifdef PC98
869                 for (i = 0; i < count; i++) {
870                         xdev = devs[i];
871                         xioport = bus_get_resource_start(xdev, SYS_RES_IOPORT, 0);
872                         xiftype = GET_IFTYPE(device_get_flags(xdev));
873                         if (device_is_enabled(xdev) && xioport > 0) {
874                             if (IS_8251(xiftype))
875                                 outb((xioport & 0xff00) | PC98SIO_cmd_port(xiftype & 0x0f), 0xf2);
876                             else
877                                 outb(xioport + if_16550a_type[xiftype & 0x0f].iat[com_mcr], 0);
878                         }
879                 }
880 #else
881                 for (i = 0; i < count; i++) {
882                         xdev = devs[i];
883                         if (device_is_enabled(xdev) &&
884                             bus_get_resource(xdev, SYS_RES_IOPORT, 0, &xioport,
885                                              NULL) == 0)
886                                 outb(xioport + com_mcr, 0);
887                 }
888 #endif
889                 free(devs, M_TEMP);
890                 already_init = TRUE;
891         }
892 #endif
893
894         if (COM_LLCONSOLE(flags)) {
895                 printf("sio%d: reserved for low-level i/o\n",
896                        device_get_unit(dev));
897                 bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
898                 device_set_softc(dev, NULL);
899                 free(com, M_DEVBUF);
900                 return (ENXIO);
901         }
902
903 #ifdef PC98
904         DELAY(10);
905
906         /*
907          * If the port is i8251 UART (internal, B98_01)
908          */
909         if (pc98_check_if_type(dev, &iod) == -1) {
910                 bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
911                 device_set_softc(dev, NULL);
912                 free(com, M_DEVBUF);
913                 return (ENXIO);
914         }
915         if (iod.irq > 0)
916                 bus_set_resource(dev, SYS_RES_IRQ, 0, iod.irq, 1);
917         if (IS_8251(iod.if_type)) {
918                 outb(iod.cmd, 0);
919                 DELAY(10);
920                 outb(iod.cmd, 0);
921                 DELAY(10);
922                 outb(iod.cmd, 0);
923                 DELAY(10);
924                 outb(iod.cmd, CMD8251_RESET);
925                 DELAY(1000);            /* for a while...*/
926                 outb(iod.cmd, 0xf2);    /* MODE (dummy) */
927                 DELAY(10);
928                 outb(iod.cmd, 0x01);    /* CMD (dummy) */
929                 DELAY(1000);            /* for a while...*/
930                 if (( inb(iod.sts) & STS8251_TxEMP ) == 0 ) {
931                     result = (ENXIO);
932                 }
933                 if (if_8251_type[iod.if_type & 0x0f].check_irq) {
934                     COM_INT_DISABLE
935                     tmp = ( inb( iod.ctrl ) & ~(IEN_Rx|IEN_TxEMP|IEN_Tx));
936                     outb( iod.ctrl, tmp|IEN_TxEMP );
937                     DELAY(10);
938                     result = isa_irq_pending() ? 0 : ENXIO;
939                     outb( iod.ctrl, tmp );
940                     COM_INT_ENABLE
941                 } else {
942                     /*
943                      * B98_01 doesn't activate TxEMP interrupt line
944                      * when being reset, so we can't check irq pending.
945                      */
946                     result = 0;
947                 }
948                 bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
949                 if (result) {
950                         device_set_softc(dev, NULL);
951                         free(com, M_DEVBUF);
952                 }
953                 return result;
954         }
955 #endif /* PC98 */
956         /*
957          * If the device is on a multiport card and has an AST/4
958          * compatible interrupt control register, initialize this
959          * register and prepare to leave MCR_IENABLE clear in the mcr.
960          * Otherwise, prepare to set MCR_IENABLE in the mcr.
961          * Point idev to the device struct giving the correct id_irq.
962          * This is the struct for the master device if there is one.
963          */
964         idev = dev;
965         mcr_image = MCR_IENABLE;
966 #ifdef COM_MULTIPORT
967         if (COM_ISMULTIPORT(flags)) {
968 #ifndef PC98
969                 Port_t xiobase;
970                 u_long io;
971 #endif
972
973                 idev = devclass_get_device(sio_devclass, COM_MPMASTER(flags));
974                 if (idev == NULL) {
975                         printf("sio%d: master device %d not configured\n",
976                                device_get_unit(dev), COM_MPMASTER(flags));
977                         idev = dev;
978                 }
979 #ifndef PC98
980                 if (!COM_NOTAST4(flags)) {
981                         if (bus_get_resource(idev, SYS_RES_IOPORT, 0, &io,
982                                              NULL) == 0) {
983                                 xiobase = io;
984                                 if (bus_get_resource(idev, SYS_RES_IRQ, 0,
985                                     NULL, NULL) == 0)
986                                         outb(xiobase + com_scr, 0x80);
987                                 else
988                                         outb(xiobase + com_scr, 0);
989                         }
990                         mcr_image = 0;
991                 }
992 #endif
993         }
994 #endif /* COM_MULTIPORT */
995         if (bus_get_resource(idev, SYS_RES_IRQ, 0, NULL, NULL) != 0)
996                 mcr_image = 0;
997
998         bzero(failures, sizeof failures);
999         iobase = rman_get_start(port);
1000
1001 #ifdef PC98
1002         if (iod.if_type == COM_IF_RSA98III) {
1003                 mcr_image = 0;
1004
1005                 outb(iobase + rsa_msr,   0x04);
1006                 outb(iobase + rsa_frr,   0x00);
1007                 if ((inb(iobase + rsa_srr) & 0x36) != 0x36) {
1008                         bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
1009                         device_set_softc(dev, NULL);
1010                         free(com, M_DEVBUF);
1011                         return (ENXIO);
1012                 }
1013                 outb(iobase + rsa_ier,   0x00);
1014                 outb(iobase + rsa_frr,   0x00);
1015                 outb(iobase + rsa_tivsr, 0x00);
1016                 outb(iobase + rsa_tcr,   0x00);
1017         }
1018
1019         tmp = if_16550a_type[iod.if_type & 0x0f].irr_write;
1020         if (tmp != -1) {
1021             /* MC16550II */
1022             int irqout;
1023             switch (isa_get_irq(idev)) {
1024             case 3: irqout = 4; break;
1025             case 5: irqout = 5; break;
1026             case 6: irqout = 6; break;
1027             case 12: irqout = 7; break;
1028             default:
1029                 printf("sio%d: irq configuration error\n",
1030                        device_get_unit(dev));
1031                 bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
1032                 device_set_softc(dev, NULL);
1033                 free(com, M_DEVBUF);
1034                 return (ENXIO);
1035             }
1036             outb((iobase & 0x00ff) | tmp, irqout);
1037         }
1038 #endif
1039
1040         /*
1041          * We don't want to get actual interrupts, just masked ones.
1042          * Interrupts from this line should already be masked in the ICU,
1043          * but mask them in the processor as well in case there are some
1044          * (misconfigured) shared interrupts.
1045          */
1046         mtx_lock_spin(&sio_lock);
1047 /* EXTRA DELAY? */
1048
1049         /*
1050          * Initialize the speed and the word size and wait long enough to
1051          * drain the maximum of 16 bytes of junk in device output queues.
1052          * The speed is undefined after a master reset and must be set
1053          * before relying on anything related to output.  There may be
1054          * junk after a (very fast) soft reboot and (apparently) after
1055          * master reset.
1056          * XXX what about the UART bug avoided by waiting in comparam()?
1057          * We don't want to to wait long enough to drain at 2 bps.
1058          */
1059         if (iobase == siocniobase)
1060                 DELAY((16 + 1) * 1000000 / (comdefaultrate / 10));
1061         else {
1062                 sio_setreg(com, com_cfcr, CFCR_DLAB | CFCR_8BITS);
1063                 divisor = siodivisor(rclk, SIO_TEST_SPEED);
1064                 sio_setreg(com, com_dlbl, divisor & 0xff);
1065                 sio_setreg(com, com_dlbh, divisor >> 8);
1066                 sio_setreg(com, com_cfcr, CFCR_8BITS);
1067                 DELAY((16 + 1) * 1000000 / (SIO_TEST_SPEED / 10));
1068         }
1069
1070         /*
1071          * Enable the interrupt gate and disable device interupts.  This
1072          * should leave the device driving the interrupt line low and
1073          * guarantee an edge trigger if an interrupt can be generated.
1074          */
1075 /* EXTRA DELAY? */
1076         sio_setreg(com, com_mcr, mcr_image);
1077         sio_setreg(com, com_ier, 0);
1078         DELAY(1000);            /* XXX */
1079         irqmap[0] = isa_irq_pending();
1080
1081         /*
1082          * Attempt to set loopback mode so that we can send a null byte
1083          * without annoying any external device.
1084          */
1085 /* EXTRA DELAY? */
1086         sio_setreg(com, com_mcr, mcr_image | MCR_LOOPBACK);
1087
1088         /*
1089          * Attempt to generate an output interrupt.  On 8250's, setting
1090          * IER_ETXRDY generates an interrupt independent of the current
1091          * setting and independent of whether the THR is empty.  On 16450's,
1092          * setting IER_ETXRDY generates an interrupt independent of the
1093          * current setting.  On 16550A's, setting IER_ETXRDY only
1094          * generates an interrupt when IER_ETXRDY is not already set.
1095          */
1096         sio_setreg(com, com_ier, IER_ETXRDY);
1097 #ifdef PC98
1098         if (iod.if_type == COM_IF_RSA98III)
1099                 outb(iobase + rsa_ier, 0x04);
1100 #endif
1101
1102         /*
1103          * On some 16x50 incompatibles, setting IER_ETXRDY doesn't generate
1104          * an interrupt.  They'd better generate one for actually doing
1105          * output.  Loopback may be broken on the same incompatibles but
1106          * it's unlikely to do more than allow the null byte out.
1107          */
1108         sio_setreg(com, com_data, 0);
1109         if (iobase == siocniobase)
1110                 DELAY((1 + 2) * 1000000 / (comdefaultrate / 10));
1111         else
1112                 DELAY((1 + 2) * 1000000 / (SIO_TEST_SPEED / 10));
1113
1114         /*
1115          * Turn off loopback mode so that the interrupt gate works again
1116          * (MCR_IENABLE was hidden).  This should leave the device driving
1117          * an interrupt line high.  It doesn't matter if the interrupt
1118          * line oscillates while we are not looking at it, since interrupts
1119          * are disabled.
1120          */
1121 /* EXTRA DELAY? */
1122         sio_setreg(com, com_mcr, mcr_image);
1123  
1124         /*
1125          * It seems my Xircom CBEM56G Cardbus modem wants to be reset
1126          * to 8 bits *again*, or else probe test 0 will fail.
1127          * gwk@sgi.com, 4/19/2001
1128          */
1129         sio_setreg(com, com_cfcr, CFCR_8BITS);
1130
1131         /*
1132          * Some PCMCIA cards (Palido 321s, DC-1S, ...) have the "TXRDY bug",
1133          * so we probe for a buggy IIR_TXRDY implementation even in the
1134          * noprobe case.  We don't probe for it in the !noprobe case because
1135          * noprobe is always set for PCMCIA cards and the problem is not
1136          * known to affect any other cards.
1137          */
1138         if (noprobe) {
1139                 /* Read IIR a few times. */
1140                 for (fn = 0; fn < 2; fn ++) {
1141                         DELAY(10000);
1142                         failures[6] = sio_getreg(com, com_iir);
1143                 }
1144
1145                 /* IIR_TXRDY should be clear.  Is it? */
1146                 result = 0;
1147                 if (failures[6] & IIR_TXRDY) {
1148                         /*
1149                          * No.  We seem to have the bug.  Does our fix for
1150                          * it work?
1151                          */
1152                         sio_setreg(com, com_ier, 0);
1153                         if (sio_getreg(com, com_iir) & IIR_NOPEND) {
1154                                 /* Yes.  We discovered the TXRDY bug! */
1155                                 SET_FLAG(dev, COM_C_IIR_TXRDYBUG);
1156                         } else {
1157                                 /* No.  Just fail.  XXX */
1158                                 result = ENXIO;
1159                                 sio_setreg(com, com_mcr, 0);
1160                         }
1161                 } else {
1162                         /* Yes.  No bug. */
1163                         CLR_FLAG(dev, COM_C_IIR_TXRDYBUG);
1164                 }
1165                 sio_setreg(com, com_ier, 0);
1166                 sio_setreg(com, com_cfcr, CFCR_8BITS);
1167                 mtx_unlock_spin(&sio_lock);
1168                 bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
1169                 if (iobase == siocniobase)
1170                         result = 0;
1171                 if (result != 0) {
1172                         device_set_softc(dev, NULL);
1173                         free(com, M_DEVBUF);
1174                 }
1175                 return (result);
1176         }
1177
1178         /*
1179          * Check that
1180          *      o the CFCR, IER and MCR in UART hold the values written to them
1181          *        (the values happen to be all distinct - this is good for
1182          *        avoiding false positive tests from bus echoes).
1183          *      o an output interrupt is generated and its vector is correct.
1184          *      o the interrupt goes away when the IIR in the UART is read.
1185          */
1186 /* EXTRA DELAY? */
1187         failures[0] = sio_getreg(com, com_cfcr) - CFCR_8BITS;
1188         failures[1] = sio_getreg(com, com_ier) - IER_ETXRDY;
1189         failures[2] = sio_getreg(com, com_mcr) - mcr_image;
1190         DELAY(10000);           /* Some internal modems need this time */
1191         irqmap[1] = isa_irq_pending();
1192         failures[4] = (sio_getreg(com, com_iir) & IIR_IMASK) - IIR_TXRDY;
1193 #ifdef PC98
1194         if (iod.if_type == COM_IF_RSA98III)
1195                 inb(iobase + rsa_srr);
1196 #endif
1197         DELAY(1000);            /* XXX */
1198         irqmap[2] = isa_irq_pending();
1199         failures[6] = (sio_getreg(com, com_iir) & IIR_IMASK) - IIR_NOPEND;
1200 #ifdef PC98
1201         if (iod.if_type == COM_IF_RSA98III)
1202                 inb(iobase + rsa_srr);
1203 #endif
1204
1205         /*
1206          * Turn off all device interrupts and check that they go off properly.
1207          * Leave MCR_IENABLE alone.  For ports without a master port, it gates
1208          * the OUT2 output of the UART to
1209          * the ICU input.  Closing the gate would give a floating ICU input
1210          * (unless there is another device driving it) and spurious interrupts.
1211          * (On the system that this was first tested on, the input floats high
1212          * and gives a (masked) interrupt as soon as the gate is closed.)
1213          */
1214         sio_setreg(com, com_ier, 0);
1215         sio_setreg(com, com_cfcr, CFCR_8BITS);  /* dummy to avoid bus echo */
1216         failures[7] = sio_getreg(com, com_ier);
1217 #ifdef PC98
1218         if (iod.if_type == COM_IF_RSA98III)
1219                 outb(iobase + rsa_ier, 0x00);
1220 #endif
1221         DELAY(1000);            /* XXX */
1222         irqmap[3] = isa_irq_pending();
1223         failures[9] = (sio_getreg(com, com_iir) & IIR_IMASK) - IIR_NOPEND;
1224 #ifdef PC98
1225         if (iod.if_type == COM_IF_RSA98III) {
1226                 inb(iobase + rsa_srr);
1227                 outb(iobase + rsa_frr, 0x00);
1228         }
1229 #endif
1230
1231         mtx_unlock_spin(&sio_lock);
1232
1233         irqs = irqmap[1] & ~irqmap[0];
1234         if (bus_get_resource(idev, SYS_RES_IRQ, 0, &xirq, NULL) == 0 &&
1235             ((1 << xirq) & irqs) == 0) {
1236                 printf(
1237                 "sio%d: configured irq %ld not in bitmap of probed irqs %#x\n",
1238                     device_get_unit(dev), xirq, irqs);
1239                 printf(
1240                 "sio%d: port may not be enabled\n",
1241                     device_get_unit(dev));
1242         }
1243         if (bootverbose)
1244                 printf("sio%d: irq maps: %#x %#x %#x %#x\n",
1245                     device_get_unit(dev),
1246                     irqmap[0], irqmap[1], irqmap[2], irqmap[3]);
1247
1248         result = 0;
1249         for (fn = 0; fn < sizeof failures; ++fn)
1250                 if (failures[fn]) {
1251                         sio_setreg(com, com_mcr, 0);
1252                         result = ENXIO;
1253                         if (bootverbose) {
1254                                 printf("sio%d: probe failed test(s):",
1255                                     device_get_unit(dev));
1256                                 for (fn = 0; fn < sizeof failures; ++fn)
1257                                         if (failures[fn])
1258                                                 printf(" %d", fn);
1259                                 printf("\n");
1260                         }
1261                         break;
1262                 }
1263         bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
1264         if (iobase == siocniobase)
1265                 result = 0;
1266         if (result != 0) {
1267                 device_set_softc(dev, NULL);
1268                 free(com, M_DEVBUF);
1269         }
1270         return (result);
1271 }
1272
1273 #ifdef COM_ESP
1274 static int
1275 espattach(com, esp_port)
1276         struct com_s            *com;
1277         Port_t                  esp_port;
1278 {
1279         u_char  dips;
1280         u_char  val;
1281
1282         /*
1283          * Check the ESP-specific I/O port to see if we're an ESP
1284          * card.  If not, return failure immediately.
1285          */
1286         if ((inb(esp_port) & 0xf3) == 0) {
1287                 printf(" port 0x%x is not an ESP board?\n", esp_port);
1288                 return (0);
1289         }
1290
1291         /*
1292          * We've got something that claims to be a Hayes ESP card.
1293          * Let's hope so.
1294          */
1295
1296         /* Get the dip-switch configuration */
1297 #ifdef PC98
1298         outb(esp_port + ESP98_CMD1, ESP_GETDIPS);
1299         dips = inb(esp_port + ESP98_STATUS1);
1300 #else
1301         outb(esp_port + ESP_CMD1, ESP_GETDIPS);
1302         dips = inb(esp_port + ESP_STATUS1);
1303 #endif
1304
1305         /*
1306          * Bits 0,1 of dips say which COM port we are.
1307          */
1308 #ifdef PC98
1309         if ((rman_get_start(com->ioportres) & 0xff) ==
1310             likely_com_ports[dips & 0x03])
1311 #else
1312         if (rman_get_start(com->ioportres) == likely_com_ports[dips & 0x03])
1313 #endif
1314                 printf(" : ESP");
1315         else {
1316                 printf(" esp_port has com %d\n", dips & 0x03);
1317                 return (0);
1318         }
1319
1320         /*
1321          * Check for ESP version 2.0 or later:  bits 4,5,6 = 010.
1322          */
1323 #ifdef PC98
1324         outb(esp_port + ESP98_CMD1, ESP_GETTEST);
1325         val = inb(esp_port + ESP98_STATUS1);    /* clear reg 1 */
1326         val = inb(esp_port + ESP98_STATUS2);
1327 #else
1328         outb(esp_port + ESP_CMD1, ESP_GETTEST);
1329         val = inb(esp_port + ESP_STATUS1);      /* clear reg 1 */
1330         val = inb(esp_port + ESP_STATUS2);
1331 #endif
1332         if ((val & 0x70) < 0x20) {
1333                 printf("-old (%o)", val & 0x70);
1334                 return (0);
1335         }
1336
1337         /*
1338          * Check for ability to emulate 16550:  bit 7 == 1
1339          */
1340         if ((dips & 0x80) == 0) {
1341                 printf(" slave");
1342                 return (0);
1343         }
1344
1345         /*
1346          * Okay, we seem to be a Hayes ESP card.  Whee.
1347          */
1348         com->esp = TRUE;
1349         com->esp_port = esp_port;
1350         return (1);
1351 }
1352 #endif /* COM_ESP */
1353
1354 int
1355 sioattach(dev, xrid, rclk)
1356         device_t        dev;
1357         int             xrid;
1358         u_long          rclk;
1359 {
1360         struct com_s    *com;
1361 #ifdef COM_ESP
1362         Port_t          *espp;
1363 #endif
1364         Port_t          iobase;
1365         int             unit;
1366         u_int           flags;
1367         int             rid;
1368         struct resource *port;
1369         int             ret;
1370         int             error;
1371         struct tty      *tp;
1372 #ifdef PC98
1373         u_char          *obuf;
1374         u_long          obufsize;
1375         int             if_type = GET_IFTYPE(device_get_flags(dev));
1376 #endif
1377
1378         rid = xrid;
1379 #ifdef PC98
1380         if (IS_8251(if_type)) {
1381                 port = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid,
1382                                               RF_ACTIVE);
1383         } else if (if_type == COM_IF_MODEM_CARD ||
1384                    if_type == COM_IF_RSA98III ||
1385                    isa_get_vendorid(dev)) {
1386                 port = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid, 0, ~0,
1387                           if_16550a_type[if_type & 0x0f].iatsz, RF_ACTIVE);
1388         } else {
1389                 port = isa_alloc_resourcev(dev, SYS_RES_IOPORT, &rid,
1390                            if_16550a_type[if_type & 0x0f].iat,
1391                            if_16550a_type[if_type & 0x0f].iatsz, RF_ACTIVE);
1392         }
1393 #else
1394         port = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid,
1395                                   0, ~0, IO_COMSIZE, RF_ACTIVE);
1396 #endif
1397         if (!port)
1398                 return (ENXIO);
1399 #ifdef PC98
1400         if (!IS_8251(if_type)) {
1401                 if (isa_load_resourcev(port,
1402                                if_16550a_type[if_type & 0x0f].iat,
1403                                if_16550a_type[if_type & 0x0f].iatsz) != 0) {
1404                         bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
1405                         return ENXIO;
1406                 }
1407         }
1408 #endif
1409
1410         iobase = rman_get_start(port);
1411         unit = device_get_unit(dev);
1412         com = device_get_softc(dev);
1413         flags = device_get_flags(dev);
1414
1415         if (unit >= sio_numunits)
1416                 sio_numunits = unit + 1;
1417
1418 #ifdef PC98
1419         obufsize = 256;
1420         if (if_type == COM_IF_RSA98III)
1421                 obufsize = 2048;
1422         if ((obuf = malloc(obufsize * 2, M_DEVBUF, M_NOWAIT)) == NULL) {
1423                 bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
1424                 return ENXIO;
1425         }
1426         bzero(obuf, obufsize * 2);
1427 #endif
1428
1429         /*
1430          * sioprobe() has initialized the device registers as follows:
1431          *      o cfcr = CFCR_8BITS.
1432          *        It is most important that CFCR_DLAB is off, so that the
1433          *        data port is not hidden when we enable interrupts.
1434          *      o ier = 0.
1435          *        Interrupts are only enabled when the line is open.
1436          *      o mcr = MCR_IENABLE, or 0 if the port has AST/4 compatible
1437          *        interrupt control register or the config specifies no irq.
1438          *        Keeping MCR_DTR and MCR_RTS off might stop the external
1439          *        device from sending before we are ready.
1440          */
1441         bzero(com, sizeof *com);
1442         com->unit = unit;
1443         com->ioportres = port;
1444         com->ioportrid = rid;
1445         com->bst = rman_get_bustag(port);
1446         com->bsh = rman_get_bushandle(port);
1447         com->cfcr_image = CFCR_8BITS;
1448         com->loses_outints = COM_LOSESOUTINTS(flags) != 0;
1449         com->no_irq = bus_get_resource(dev, SYS_RES_IRQ, 0, NULL, NULL) != 0;
1450         com->tx_fifo_size = 1;
1451 #ifdef PC98
1452         com->obufsize = obufsize;
1453         com->obuf1 = obuf;
1454         com->obuf2 = obuf + obufsize;
1455 #endif
1456         com->obufs[0].l_head = com->obuf1;
1457         com->obufs[1].l_head = com->obuf2;
1458
1459 #ifdef PC98
1460         com->pc98_if_type = if_type;
1461
1462         if (IS_8251(if_type)) {
1463             pc98_set_ioport(com);
1464
1465             if (if_type == COM_IF_INTERNAL && pc98_check_8251fifo()) {
1466                 com->pc98_8251fifo = 1;
1467                 com->pc98_8251fifo_enable = 0;
1468             }
1469         } else {
1470             bus_addr_t  *iat = if_16550a_type[if_type & 0x0f].iat;
1471
1472             com->data_port = iobase + iat[com_data];
1473             com->int_ctl_port = iobase + iat[com_ier];
1474             com->int_id_port = iobase + iat[com_iir];
1475             com->modem_ctl_port = iobase + iat[com_mcr];
1476             com->mcr_image = inb(com->modem_ctl_port);
1477             com->line_status_port = iobase + iat[com_lsr];
1478             com->modem_status_port = iobase + iat[com_msr];
1479         }
1480 #else /* not PC98 */
1481         com->data_port = iobase + com_data;
1482         com->int_ctl_port = iobase + com_ier;
1483         com->int_id_port = iobase + com_iir;
1484         com->modem_ctl_port = iobase + com_mcr;
1485         com->mcr_image = inb(com->modem_ctl_port);
1486         com->line_status_port = iobase + com_lsr;
1487         com->modem_status_port = iobase + com_msr;
1488 #endif
1489
1490         tp = com->tp = ttyalloc();
1491         tp->t_oproc = comstart;
1492         tp->t_param = comparam;
1493         tp->t_stop = comstop;
1494         tp->t_modem = commodem;
1495         tp->t_break = combreak;
1496         tp->t_close = comclose;
1497         tp->t_open = comopen;
1498         tp->t_sc = com;
1499
1500 #ifdef PC98
1501         if (!IS_8251(if_type) && rclk == 0)
1502                 rclk = if_16550a_type[if_type & 0x0f].rclk;
1503 #else
1504         if (rclk == 0)
1505                 rclk = DEFAULT_RCLK;
1506 #endif
1507         com->rclk = rclk;
1508
1509         if (unit == comconsole)
1510                 ttyconsolemode(tp, comdefaultrate);
1511         error = siosetwater(com, tp->t_init_in.c_ispeed);
1512         mtx_unlock_spin(&sio_lock);
1513         if (error) {
1514                 /*
1515                  * Leave i/o resources allocated if this is a `cn'-level
1516                  * console, so that other devices can't snarf them.
1517                  */
1518                 if (iobase != siocniobase)
1519                         bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
1520                 return (ENOMEM);
1521         }
1522
1523         /* attempt to determine UART type */
1524         printf("sio%d: type", unit);
1525
1526 #ifndef PC98
1527         if (!COM_ISMULTIPORT(flags) &&
1528             !COM_IIR_TXRDYBUG(flags) && !COM_NOSCR(flags)) {
1529                 u_char  scr;
1530                 u_char  scr1;
1531                 u_char  scr2;
1532
1533                 scr = sio_getreg(com, com_scr);
1534                 sio_setreg(com, com_scr, 0xa5);
1535                 scr1 = sio_getreg(com, com_scr);
1536                 sio_setreg(com, com_scr, 0x5a);
1537                 scr2 = sio_getreg(com, com_scr);
1538                 sio_setreg(com, com_scr, scr);
1539                 if (scr1 != 0xa5 || scr2 != 0x5a) {
1540                         printf(" 8250 or not responding");
1541                         goto determined_type;
1542                 }
1543         }
1544 #endif /* !PC98 */
1545 #ifdef PC98
1546         if (IS_8251(com->pc98_if_type)) {
1547             if (com->pc98_8251fifo && !COM_NOFIFO(flags))
1548                 com->tx_fifo_size = 16;
1549             com_int_TxRx_disable( com );
1550             com_cflag_and_speed_set( com, tp->t_init_in.c_cflag, comdefaultrate );
1551             com_tiocm_bic( com, TIOCM_DTR|TIOCM_RTS|TIOCM_LE );
1552             com_send_break_off( com );
1553
1554             if (com->pc98_if_type == COM_IF_INTERNAL) {
1555                 printf(" (internal%s%s)",
1556                        com->pc98_8251fifo ? " fifo" : "",
1557                        PC98SIO_baud_rate_port(com->pc98_if_type) != -1 ?
1558                        " v-fast" : "");
1559             } else {
1560                 printf(" 8251%s", if_8251_type[com->pc98_if_type & 0x0f].name);
1561             }
1562         } else {
1563 #endif /* PC98 */
1564         sio_setreg(com, com_fifo, FIFO_ENABLE | FIFO_RX_HIGH);
1565         DELAY(100);
1566         switch (inb(com->int_id_port) & IIR_FIFO_MASK) {
1567         case FIFO_RX_LOW:
1568                 printf(" 16450");
1569                 break;
1570         case FIFO_RX_MEDL:
1571                 printf(" 16450?");
1572                 break;
1573         case FIFO_RX_MEDH:
1574                 printf(" 16550?");
1575                 break;
1576         case FIFO_RX_HIGH:
1577                 if (COM_NOFIFO(flags)) {
1578                         printf(" 16550A fifo disabled");
1579                         break;
1580                 }
1581                 com->hasfifo = TRUE;
1582 #ifdef PC98
1583                 if (com->pc98_if_type == COM_IF_RSA98III) {
1584                         com->tx_fifo_size = 2048;
1585                         com->rsabase = iobase;
1586                         outb(com->rsabase + rsa_ier, 0x00);
1587                         outb(com->rsabase + rsa_frr, 0x00);
1588                 }
1589 #else
1590                 if (COM_ST16650A(flags)) {
1591                         printf(" ST16650A");
1592                         com->st16650a = TRUE;
1593                         com->tx_fifo_size = 32;
1594                         break;
1595                 }
1596                 if (COM_TI16754(flags)) {
1597                         printf(" TI16754");
1598                         com->tx_fifo_size = 64;
1599                         break;
1600                 }
1601 #endif
1602                 printf(" 16550A");
1603 #ifdef COM_ESP
1604 #ifdef PC98
1605                 if (com->pc98_if_type == COM_IF_ESP98)
1606 #endif
1607                 for (espp = likely_esp_ports; *espp != 0; espp++)
1608                         if (espattach(com, *espp)) {
1609                                 com->tx_fifo_size = 1024;
1610                                 break;
1611                         }
1612                 if (com->esp)
1613                         break;
1614 #endif
1615 #ifdef PC98
1616                 com->tx_fifo_size = 16;
1617 #else
1618                 com->tx_fifo_size = COM_FIFOSIZE(flags);
1619                 if (com->tx_fifo_size == 0)
1620                         com->tx_fifo_size = 16;
1621                 else
1622                         printf(" lookalike with %u bytes FIFO",
1623                                com->tx_fifo_size);
1624 #endif
1625                 break;
1626         }
1627         
1628 #ifdef PC98
1629         if (com->pc98_if_type == COM_IF_RSB3000) {
1630             /* Set RSB-2000/3000 Extended Buffer mode. */
1631             u_char lcr;
1632             lcr = sio_getreg(com, com_cfcr);
1633             sio_setreg(com, com_cfcr, lcr | CFCR_DLAB);
1634             sio_setreg(com, com_emr, EMR_EXBUFF | EMR_EFMODE);
1635             sio_setreg(com, com_cfcr, lcr);
1636         }
1637 #endif
1638
1639 #ifdef COM_ESP
1640         if (com->esp) {
1641                 /*
1642                  * Set 16550 compatibility mode.
1643                  * We don't use the ESP_MODE_SCALE bit to increase the
1644                  * fifo trigger levels because we can't handle large
1645                  * bursts of input.
1646                  * XXX flow control should be set in comparam(), not here.
1647                  */
1648 #ifdef PC98
1649                 outb(com->esp_port + ESP98_CMD1, ESP_SETMODE);
1650                 outb(com->esp_port + ESP98_CMD2, ESP_MODE_RTS | ESP_MODE_FIFO);
1651 #else
1652                 outb(com->esp_port + ESP_CMD1, ESP_SETMODE);
1653                 outb(com->esp_port + ESP_CMD2, ESP_MODE_RTS | ESP_MODE_FIFO);
1654 #endif
1655
1656                 /* Set RTS/CTS flow control. */
1657 #ifdef PC98
1658                 outb(com->esp_port + ESP98_CMD1, ESP_SETFLOWTYPE);
1659                 outb(com->esp_port + ESP98_CMD2, ESP_FLOW_RTS);
1660                 outb(com->esp_port + ESP98_CMD2, ESP_FLOW_CTS);
1661 #else
1662                 outb(com->esp_port + ESP_CMD1, ESP_SETFLOWTYPE);
1663                 outb(com->esp_port + ESP_CMD2, ESP_FLOW_RTS);
1664                 outb(com->esp_port + ESP_CMD2, ESP_FLOW_CTS);
1665 #endif
1666
1667                 /* Set flow-control levels. */
1668 #ifdef PC98
1669                 outb(com->esp_port + ESP98_CMD1, ESP_SETRXFLOW);
1670                 outb(com->esp_port + ESP98_CMD2, HIBYTE(768));
1671                 outb(com->esp_port + ESP98_CMD2, LOBYTE(768));
1672                 outb(com->esp_port + ESP98_CMD2, HIBYTE(512));
1673                 outb(com->esp_port + ESP98_CMD2, LOBYTE(512));
1674 #else
1675                 outb(com->esp_port + ESP_CMD1, ESP_SETRXFLOW);
1676                 outb(com->esp_port + ESP_CMD2, HIBYTE(768));
1677                 outb(com->esp_port + ESP_CMD2, LOBYTE(768));
1678                 outb(com->esp_port + ESP_CMD2, HIBYTE(512));
1679                 outb(com->esp_port + ESP_CMD2, LOBYTE(512));
1680 #endif
1681
1682 #ifdef PC98
1683                 /* Set UART clock prescaler. */
1684                 outb(com->esp_port + ESP98_CMD1, ESP_SETCLOCK);
1685                 outb(com->esp_port + ESP98_CMD2, 2);    /* 4 times */
1686 #endif
1687         }
1688 #endif /* COM_ESP */
1689         sio_setreg(com, com_fifo, 0);
1690 #ifdef PC98
1691         printf("%s", if_16550a_type[com->pc98_if_type & 0x0f].name);
1692 #else
1693 determined_type: ;
1694 #endif
1695
1696 #ifdef COM_MULTIPORT
1697         if (COM_ISMULTIPORT(flags)) {
1698                 device_t masterdev;
1699
1700                 com->multiport = TRUE;
1701                 printf(" (multiport");
1702                 if (unit == COM_MPMASTER(flags))
1703                         printf(" master");
1704                 printf(")");
1705                 masterdev = devclass_get_device(sio_devclass,
1706                     COM_MPMASTER(flags));
1707                 com->no_irq = (masterdev == NULL || bus_get_resource(masterdev,
1708                     SYS_RES_IRQ, 0, NULL, NULL) != 0);
1709          }
1710 #endif /* COM_MULTIPORT */
1711 #ifdef PC98
1712         }
1713 #endif
1714         if (unit == comconsole)
1715                 printf(", console");
1716         if (COM_IIR_TXRDYBUG(flags))
1717                 printf(" with a buggy IIR_TXRDY implementation");
1718         printf("\n");
1719
1720         if (sio_fast_ih == NULL) {
1721                 swi_add(&tty_intr_event, "sio", siopoll, NULL, SWI_TTY, 0,
1722                     &sio_fast_ih);
1723                 swi_add(&clk_intr_event, "sio", siopoll, NULL, SWI_CLOCK, 0,
1724                     &sio_slow_ih);
1725         }
1726
1727         com->flags = flags;
1728         com->pps.ppscap = PPS_CAPTUREASSERT | PPS_CAPTURECLEAR;
1729         tp->t_pps = &com->pps;
1730
1731         if (COM_PPSCTS(flags))
1732                 com->pps_bit = MSR_CTS;
1733         else
1734                 com->pps_bit = MSR_DCD;
1735         pps_init(&com->pps);
1736
1737         rid = 0;
1738         com->irqres = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_ACTIVE);
1739         if (com->irqres) {
1740                 ret = BUS_SETUP_INTR(device_get_parent(dev), dev, com->irqres,
1741                                      INTR_TYPE_TTY | INTR_FAST,
1742                                      siointr, com, &com->cookie);
1743                 if (ret) {
1744                         ret = BUS_SETUP_INTR(device_get_parent(dev), dev,
1745                                              com->irqres, INTR_TYPE_TTY,
1746                                              siointr, com, &com->cookie);
1747                         if (ret == 0)
1748                                 device_printf(dev, "unable to activate interrupt in fast mode - using normal mode\n");
1749                 }
1750                 if (ret)
1751                         device_printf(dev, "could not activate interrupt\n");
1752 #if defined(KDB) && (defined(BREAK_TO_DEBUGGER) || \
1753     defined(ALT_BREAK_TO_DEBUGGER))
1754                 /*
1755                  * Enable interrupts for early break-to-debugger support
1756                  * on the console.
1757                  */
1758                 if (ret == 0 && unit == comconsole)
1759                         outb(siocniobase + com_ier, IER_ERXRDY | IER_ERLS |
1760                             IER_EMSC);
1761 #endif
1762         }
1763
1764         /* We're ready, open the doors... */
1765         ttycreate(tp, NULL, unit, MINOR_CALLOUT, "d%r", unit);
1766
1767         return (0);
1768 }
1769
1770 static int
1771 comopen(struct tty *tp, struct cdev *dev)
1772 {
1773         struct com_s    *com;
1774         int i;
1775
1776         com = tp->t_sc;
1777         com->poll = com->no_irq;
1778         com->poll_output = com->loses_outints;
1779 #ifdef PC98
1780         if (IS_8251(com->pc98_if_type)) {
1781                 com_tiocm_bis(com, TIOCM_DTR|TIOCM_RTS);
1782                 pc98_msrint_start(dev);
1783                 if (com->pc98_8251fifo) {
1784                         com->pc98_8251fifo_enable = 1;
1785                         outb(I8251F_fcr, CTRL8251F_ENABLE |
1786                              CTRL8251F_XMT_RST | CTRL8251F_RCV_RST);
1787                 }
1788         }
1789 #endif
1790         if (com->hasfifo) {
1791                 /*
1792                  * (Re)enable and drain fifos.
1793                  *
1794                  * Certain SMC chips cause problems if the fifos
1795                  * are enabled while input is ready.  Turn off the
1796                  * fifo if necessary to clear the input.  We test
1797                  * the input ready bit after enabling the fifos
1798                  * since we've already enabled them in comparam()
1799                  * and to handle races between enabling and fresh
1800                  * input.
1801                  */
1802                 for (i = 0; i < 500; i++) {
1803                         sio_setreg(com, com_fifo,
1804                                    FIFO_RCV_RST | FIFO_XMT_RST
1805                                    | com->fifo_image);
1806 #ifdef PC98
1807                         if (com->pc98_if_type == COM_IF_RSA98III)
1808                                 outb(com->rsabase + rsa_frr , 0x00);
1809 #endif
1810                         /*
1811                          * XXX the delays are for superstitious
1812                          * historical reasons.  It must be less than
1813                          * the character time at the maximum
1814                          * supported speed (87 usec at 115200 bps
1815                          * 8N1).  Otherwise we might loop endlessly
1816                          * if data is streaming in.  We used to use
1817                          * delays of 100.  That usually worked
1818                          * because DELAY(100) used to usually delay
1819                          * for about 85 usec instead of 100.
1820                          */
1821                         DELAY(50);
1822 #ifdef PC98
1823                         if (com->pc98_if_type == COM_IF_RSA98III ?
1824                             !(inb(com->rsabase + rsa_srr) & 0x08) :
1825                             !(inb(com->line_status_port) & LSR_RXRDY))
1826                                 break;
1827 #else
1828                         if (!(inb(com->line_status_port) & LSR_RXRDY))
1829                                 break;
1830 #endif
1831                         sio_setreg(com, com_fifo, 0);
1832                         DELAY(50);
1833                         (void) inb(com->data_port);
1834                 }
1835                 if (i == 500)
1836                         return (EIO);
1837         }
1838
1839         mtx_lock_spin(&sio_lock);
1840 #ifdef PC98
1841         if (IS_8251(com->pc98_if_type)) {
1842                 com_tiocm_bis(com, TIOCM_LE);
1843                 com->pc98_prev_modem_status = pc98_get_modem_status(com);
1844                 com_int_Rx_enable(com);
1845         } else {
1846 #endif
1847         (void) inb(com->line_status_port);
1848         (void) inb(com->data_port);
1849         com->prev_modem_status = com->last_modem_status
1850             = inb(com->modem_status_port);
1851         outb(com->int_ctl_port,
1852              IER_ERXRDY | IER_ERLS | IER_EMSC
1853              | (COM_IIR_TXRDYBUG(com->flags) ? 0 : IER_ETXRDY));
1854 #ifdef PC98
1855         if (com->pc98_if_type == COM_IF_RSA98III) {
1856                 outb(com->rsabase + rsa_ier, 0x1d);
1857                 outb(com->int_ctl_port, IER_ERLS | IER_EMSC);
1858         }
1859 #endif
1860 #ifdef PC98
1861         }
1862 #endif
1863         mtx_unlock_spin(&sio_lock);
1864         siosettimeout();
1865         /* XXX: should be generic ? */
1866 #ifdef PC98
1867         if ((IS_8251(com->pc98_if_type) &&
1868              (pc98_get_modem_status(com) & TIOCM_CAR)) ||
1869             (!IS_8251(com->pc98_if_type) &&
1870              (com->prev_modem_status & MSR_DCD)) ||
1871             ISCALLOUT(dev))
1872                 ttyld_modem(tp, 1);
1873 #else
1874         if (com->prev_modem_status & MSR_DCD || ISCALLOUT(dev))
1875                 ttyld_modem(tp, 1);
1876 #endif
1877         return (0);
1878 }
1879
1880 static void
1881 comclose(tp)
1882         struct tty      *tp;
1883 {
1884         int             s;
1885         struct com_s    *com;
1886
1887         s = spltty();
1888         com = tp->t_sc;
1889         com->poll = FALSE;
1890         com->poll_output = FALSE;
1891 #ifdef PC98
1892         com_send_break_off(com);
1893 #else
1894         sio_setreg(com, com_cfcr, com->cfcr_image &= ~CFCR_SBREAK);
1895 #endif
1896
1897 #if defined(KDB) && (defined(BREAK_TO_DEBUGGER) || \
1898     defined(ALT_BREAK_TO_DEBUGGER))
1899         /*
1900          * Leave interrupts enabled and don't clear DTR if this is the
1901          * console. This allows us to detect break-to-debugger events
1902          * while the console device is closed.
1903          */
1904         if (com->unit != comconsole)
1905 #endif
1906         {
1907 #ifdef PC98
1908                 int     tmp;
1909                 if (IS_8251(com->pc98_if_type))
1910                         com_int_TxRx_disable(com);
1911                 else
1912                         sio_setreg(com, com_ier, 0);
1913                 if (com->pc98_if_type == COM_IF_RSA98III)
1914                         outb(com->rsabase + rsa_ier, 0x00);
1915                 if (IS_8251(com->pc98_if_type))
1916                         tmp = pc98_get_modem_status(com) & TIOCM_CAR;
1917                 else
1918                         tmp = com->prev_modem_status & MSR_DCD;
1919 #else
1920                 sio_setreg(com, com_ier, 0);
1921 #endif
1922                 if (tp->t_cflag & HUPCL
1923                     /*
1924                      * XXX we will miss any carrier drop between here and the
1925                      * next open.  Perhaps we should watch DCD even when the
1926                      * port is closed; it is not sufficient to check it at
1927                      * the next open because it might go up and down while
1928                      * we're not watching.
1929                      */
1930                     || (!tp->t_actout
1931 #ifdef PC98
1932                         && !(tmp)
1933 #else
1934                         && !(com->prev_modem_status & MSR_DCD)
1935 #endif
1936                         && !(tp->t_init_in.c_cflag & CLOCAL))
1937                     || !(tp->t_state & TS_ISOPEN)) {
1938 #ifdef PC98
1939                         if (IS_8251(com->pc98_if_type))
1940                             com_tiocm_bic(com, TIOCM_DTR|TIOCM_RTS|TIOCM_LE);
1941                         else
1942 #endif
1943                         (void)commodem(tp, 0, SER_DTR);
1944                         ttydtrwaitstart(tp);
1945                 }
1946 #ifdef PC98
1947                 else {
1948                         if (IS_8251(com->pc98_if_type))
1949                                 com_tiocm_bic(com, TIOCM_LE);
1950                 }
1951 #endif
1952         }
1953 #ifdef PC98
1954         if (com->pc98_8251fifo) {
1955             if (com->pc98_8251fifo_enable)
1956                 outb(I8251F_fcr, CTRL8251F_XMT_RST | CTRL8251F_RCV_RST);
1957             com->pc98_8251fifo_enable = 0;
1958         }
1959 #endif
1960         if (com->hasfifo) {
1961                 /*
1962                  * Disable fifos so that they are off after controlled
1963                  * reboots.  Some BIOSes fail to detect 16550s when the
1964                  * fifos are enabled.
1965                  */
1966                 sio_setreg(com, com_fifo, 0);
1967         }
1968         tp->t_actout = FALSE;
1969         wakeup(&tp->t_actout);
1970         wakeup(TSA_CARR_ON(tp));        /* restart any wopeners */
1971         siosettimeout();
1972         splx(s);
1973 }
1974
1975 static void
1976 siobusycheck(chan)
1977         void    *chan;
1978 {
1979         struct com_s    *com;
1980         int             s;
1981
1982         com = (struct com_s *)chan;
1983
1984         /*
1985          * Clear TS_BUSY if low-level output is complete.
1986          * spl locking is sufficient because siointr1() does not set CS_BUSY.
1987          * If siointr1() clears CS_BUSY after we look at it, then we'll get
1988          * called again.  Reading the line status port outside of siointr1()
1989          * is safe because CS_BUSY is clear so there are no output interrupts
1990          * to lose.
1991          */
1992         s = spltty();
1993         if (com->state & CS_BUSY)
1994                 com->extra_state &= ~CSE_BUSYCHECK;     /* False alarm. */
1995 #ifdef  PC98
1996         else if ((IS_8251(com->pc98_if_type) &&
1997                   ((com->pc98_8251fifo_enable &&
1998                     (inb(I8251F_lsr) & (STS8251F_TxRDY | STS8251F_TxEMP))
1999                     == (STS8251F_TxRDY | STS8251F_TxEMP)) ||
2000                    (!com->pc98_8251fifo_enable &&
2001                     (inb(com->sts_port) & (STS8251_TxRDY | STS8251_TxEMP))
2002                     == (STS8251_TxRDY | STS8251_TxEMP)))) ||
2003                  ((inb(com->line_status_port) & (LSR_TSRE | LSR_TXRDY))
2004                   == (LSR_TSRE | LSR_TXRDY))) {
2005 #else
2006         else if ((inb(com->line_status_port) & (LSR_TSRE | LSR_TXRDY))
2007             == (LSR_TSRE | LSR_TXRDY)) {
2008 #endif
2009                 com->tp->t_state &= ~TS_BUSY;
2010                 ttwwakeup(com->tp);
2011                 com->extra_state &= ~CSE_BUSYCHECK;
2012         } else
2013                 timeout(siobusycheck, com, hz / 100);
2014         splx(s);
2015 }
2016
2017 static u_int
2018 siodivisor(rclk, speed)
2019         u_long  rclk;
2020         speed_t speed;
2021 {
2022         long    actual_speed;
2023         u_int   divisor;
2024         int     error;
2025
2026         if (speed == 0)
2027                 return (0);
2028 #if UINT_MAX > (ULONG_MAX - 1) / 8
2029         if (speed > (ULONG_MAX - 1) / 8)
2030                 return (0);
2031 #endif
2032         divisor = (rclk / (8UL * speed) + 1) / 2;
2033         if (divisor == 0 || divisor >= 65536)
2034                 return (0);
2035         actual_speed = rclk / (16UL * divisor);
2036
2037         /* 10 times error in percent: */
2038         error = ((actual_speed - (long)speed) * 2000 / (long)speed + 1) / 2;
2039
2040         /* 3.0% maximum error tolerance: */
2041         if (error < -30 || error > 30)
2042                 return (0);
2043
2044         return (divisor);
2045 }
2046
2047 /*
2048  * Call this function with the sio_lock mutex held.  It will return with the
2049  * lock still held.
2050  */
2051 static void
2052 sioinput(com)
2053         struct com_s    *com;
2054 {
2055         u_char          *buf;
2056         int             incc;
2057         u_char          line_status;
2058         int             recv_data;
2059         struct tty      *tp;
2060
2061         buf = com->ibuf;
2062         tp = com->tp;
2063         if (!(tp->t_state & TS_ISOPEN) || !(tp->t_cflag & CREAD)) {
2064                 com_events -= (com->iptr - com->ibuf);
2065                 com->iptr = com->ibuf;
2066                 return;
2067         }
2068         if (tp->t_state & TS_CAN_BYPASS_L_RINT) {
2069                 /*
2070                  * Avoid the grotesquely inefficient lineswitch routine
2071                  * (ttyinput) in "raw" mode.  It usually takes about 450
2072                  * instructions (that's without canonical processing or echo!).
2073                  * slinput is reasonably fast (usually 40 instructions plus
2074                  * call overhead).
2075                  */
2076                 do {
2077                         /*
2078                          * This may look odd, but it is using save-and-enable
2079                          * semantics instead of the save-and-disable semantics
2080                          * that are used everywhere else.
2081                          */
2082                         mtx_unlock_spin(&sio_lock);
2083                         incc = com->iptr - buf;
2084                         if (tp->t_rawq.c_cc + incc > tp->t_ihiwat
2085                             && (com->state & CS_RTS_IFLOW
2086                                 || tp->t_iflag & IXOFF)
2087                             && !(tp->t_state & TS_TBLOCK))
2088                                 ttyblock(tp);
2089                         com->delta_error_counts[CE_TTY_BUF_OVERFLOW]
2090                                 += b_to_q((char *)buf, incc, &tp->t_rawq);
2091                         buf += incc;
2092                         tk_nin += incc;
2093                         tk_rawcc += incc;
2094                         tp->t_rawcc += incc;
2095                         ttwakeup(tp);
2096                         if (tp->t_state & TS_TTSTOP
2097                             && (tp->t_iflag & IXANY
2098                                 || tp->t_cc[VSTART] == tp->t_cc[VSTOP])) {
2099                                 tp->t_state &= ~TS_TTSTOP;
2100                                 tp->t_lflag &= ~FLUSHO;
2101                                 comstart(tp);
2102                         }
2103                         mtx_lock_spin(&sio_lock);
2104                 } while (buf < com->iptr);
2105         } else {
2106                 do {
2107                         /*
2108                          * This may look odd, but it is using save-and-enable
2109                          * semantics instead of the save-and-disable semantics
2110                          * that are used everywhere else.
2111                          */
2112                         mtx_unlock_spin(&sio_lock);
2113                         line_status = buf[com->ierroff];
2114                         recv_data = *buf++;
2115                         if (line_status
2116                             & (LSR_BI | LSR_FE | LSR_OE | LSR_PE)) {
2117                                 if (line_status & LSR_BI)
2118                                         recv_data |= TTY_BI;
2119                                 if (line_status & LSR_FE)
2120                                         recv_data |= TTY_FE;
2121                                 if (line_status & LSR_OE)
2122                                         recv_data |= TTY_OE;
2123                                 if (line_status & LSR_PE)
2124                                         recv_data |= TTY_PE;
2125                         }
2126                         ttyld_rint(tp, recv_data);
2127                         mtx_lock_spin(&sio_lock);
2128                 } while (buf < com->iptr);
2129         }
2130         com_events -= (com->iptr - com->ibuf);
2131         com->iptr = com->ibuf;
2132
2133         /*
2134          * There is now room for another low-level buffer full of input,
2135          * so enable RTS if it is now disabled and there is room in the
2136          * high-level buffer.
2137          */
2138 #ifdef PC98
2139         if (IS_8251(com->pc98_if_type)) {
2140                 if ((com->state & CS_RTS_IFLOW) &&
2141                     !(com_tiocm_get(com) & TIOCM_RTS) &&
2142                     !(tp->t_state & TS_TBLOCK))
2143                         com_tiocm_bis(com, TIOCM_RTS);
2144         } else {
2145                 if ((com->state & CS_RTS_IFLOW) &&
2146                     !(com->mcr_image & MCR_RTS) &&
2147                     !(tp->t_state & TS_TBLOCK))
2148                         outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
2149         }
2150 #else
2151         if ((com->state & CS_RTS_IFLOW) && !(com->mcr_image & MCR_RTS) &&
2152             !(tp->t_state & TS_TBLOCK))
2153                 outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
2154 #endif
2155 }
2156
2157 static void
2158 siointr(arg)
2159         void            *arg;
2160 {
2161         struct com_s    *com;
2162 #if defined(PC98) && defined(COM_MULTIPORT)
2163         u_char          rsa_buf_status;
2164 #endif
2165
2166 #ifndef COM_MULTIPORT
2167         com = (struct com_s *)arg;
2168
2169         mtx_lock_spin(&sio_lock);
2170         siointr1(com);
2171         mtx_unlock_spin(&sio_lock);
2172 #else /* COM_MULTIPORT */
2173         bool_t          possibly_more_intrs;
2174         int             unit;
2175
2176         /*
2177          * Loop until there is no activity on any port.  This is necessary
2178          * to get an interrupt edge more than to avoid another interrupt.
2179          * If the IRQ signal is just an OR of the IRQ signals from several
2180          * devices, then the edge from one may be lost because another is
2181          * on.
2182          */
2183         mtx_lock_spin(&sio_lock);
2184         do {
2185                 possibly_more_intrs = FALSE;
2186                 for (unit = 0; unit < sio_numunits; ++unit) {
2187                         com = com_addr(unit);
2188                         /*
2189                          * XXX COM_LOCK();
2190                          * would it work here, or be counter-productive?
2191                          */
2192 #ifdef PC98
2193                         if (com != NULL 
2194                             && !com->gone
2195                             && IS_8251(com->pc98_if_type)) {
2196                                 siointr1(com);
2197                         } else if (com != NULL 
2198                             && !com->gone
2199                             && com->pc98_if_type == COM_IF_RSA98III) {
2200                                 rsa_buf_status =
2201                                     inb(com->rsabase + rsa_srr) & 0xc9;
2202                                 if ((rsa_buf_status & 0xc8)
2203                                     || !(rsa_buf_status & 0x01)) {
2204                                     siointr1(com);
2205                                     if (rsa_buf_status !=
2206                                         (inb(com->rsabase + rsa_srr) & 0xc9))
2207                                         possibly_more_intrs = TRUE;
2208                                 }
2209                         } else
2210 #endif
2211                         if (com != NULL 
2212                             && !com->gone
2213                             && (inb(com->int_id_port) & IIR_IMASK)
2214                                != IIR_NOPEND) {
2215                                 siointr1(com);
2216                                 possibly_more_intrs = TRUE;
2217                         }
2218                         /* XXX COM_UNLOCK(); */
2219                 }
2220         } while (possibly_more_intrs);
2221         mtx_unlock_spin(&sio_lock);
2222 #endif /* COM_MULTIPORT */
2223 }
2224
2225 static struct timespec siots[8];
2226 static int siotso;
2227 static int volatile siotsunit = -1;
2228
2229 static int
2230 sysctl_siots(SYSCTL_HANDLER_ARGS)
2231 {
2232         char buf[128];
2233         long long delta;
2234         size_t len;
2235         int error, i, tso;
2236
2237         for (i = 1, tso = siotso; i < tso; i++) {
2238                 delta = (long long)(siots[i].tv_sec - siots[i - 1].tv_sec) *
2239                     1000000000 +
2240                     (siots[i].tv_nsec - siots[i - 1].tv_nsec);
2241                 len = sprintf(buf, "%lld\n", delta);
2242                 if (delta >= 110000)
2243                         len += sprintf(buf + len - 1, ": *** %ld.%09ld\n",
2244                             (long)siots[i].tv_sec, siots[i].tv_nsec) - 1;
2245                 if (i == tso - 1)
2246                         buf[len - 1] = '\0';
2247                 error = SYSCTL_OUT(req, buf, len);
2248                 if (error != 0)
2249                         return (error);
2250                 uio_yield();
2251         }
2252         return (0);
2253 }
2254
2255 SYSCTL_PROC(_machdep, OID_AUTO, siots, CTLTYPE_STRING | CTLFLAG_RD,
2256     0, 0, sysctl_siots, "A", "sio timestamps");
2257
2258 static void
2259 siointr1(com)
2260         struct com_s    *com;
2261 {
2262         u_char  int_ctl;
2263         u_char  int_ctl_new;
2264         u_char  line_status;
2265         u_char  modem_status;
2266         u_char  *ioptr;
2267         u_char  recv_data;
2268
2269 #ifdef PC98
2270         u_char  tmp = 0;
2271         u_char  rsa_buf_status = 0;
2272         int     rsa_tx_fifo_size = 0;
2273 #endif /* PC98 */
2274
2275         if (COM_IIR_TXRDYBUG(com->flags)) {
2276                 int_ctl = inb(com->int_ctl_port);
2277                 int_ctl_new = int_ctl;
2278         } else {
2279                 int_ctl = 0;
2280                 int_ctl_new = 0;
2281         }
2282
2283         while (!com->gone) {
2284 #ifdef PC98
2285 status_read:;
2286                 if (IS_8251(com->pc98_if_type)) {
2287                         if (com->pc98_8251fifo_enable)
2288                                 tmp = inb(I8251F_lsr);
2289                         else
2290                                 tmp = inb(com->sts_port);
2291 more_intr:
2292                         line_status = 0;
2293                         if (com->pc98_8251fifo_enable) {
2294                             if (tmp & STS8251F_TxRDY) line_status |= LSR_TXRDY;
2295                             if (tmp & STS8251F_RxRDY) line_status |= LSR_RXRDY;
2296                             if (tmp & STS8251F_TxEMP) line_status |= LSR_TSRE;
2297                             if (tmp & STS8251F_PE)    line_status |= LSR_PE;
2298                             if (tmp & STS8251F_OE)    line_status |= LSR_OE;
2299                             if (tmp & STS8251F_BD_SD) line_status |= LSR_BI;
2300                         } else {
2301                             if (tmp & STS8251_TxRDY)  line_status |= LSR_TXRDY;
2302                             if (tmp & STS8251_RxRDY)  line_status |= LSR_RXRDY;
2303                             if (tmp & STS8251_TxEMP)  line_status |= LSR_TSRE;
2304                             if (tmp & STS8251_PE)     line_status |= LSR_PE;
2305                             if (tmp & STS8251_OE)     line_status |= LSR_OE;
2306                             if (tmp & STS8251_FE)     line_status |= LSR_FE;
2307                             if (tmp & STS8251_BD_SD)  line_status |= LSR_BI;
2308                         }
2309                 } else {
2310 #endif /* PC98 */
2311                 if (com->pps.ppsparam.mode & PPS_CAPTUREBOTH) {
2312                         modem_status = inb(com->modem_status_port);
2313                         if ((modem_status ^ com->last_modem_status) &
2314                             com->pps_bit) {
2315                                 pps_capture(&com->pps);
2316                                 pps_event(&com->pps,
2317                                     (modem_status & com->pps_bit) ? 
2318                                     PPS_CAPTUREASSERT : PPS_CAPTURECLEAR);
2319                         }
2320                 }
2321                 line_status = inb(com->line_status_port);
2322 #ifdef PC98
2323                 }
2324                 if (com->pc98_if_type == COM_IF_RSA98III)
2325                         rsa_buf_status = inb(com->rsabase + rsa_srr);
2326 #endif /* PC98 */
2327
2328                 /* input event? (check first to help avoid overruns) */
2329 #ifndef PC98
2330                 while (line_status & LSR_RCV_MASK) {
2331 #else
2332                 while ((line_status & LSR_RCV_MASK)
2333                        || (com->pc98_if_type == COM_IF_RSA98III
2334                            && (rsa_buf_status & 0x08))) {
2335 #endif /* PC98 */
2336                         /* break/unnattached error bits or real input? */
2337 #ifdef PC98
2338                         if (IS_8251(com->pc98_if_type)) {
2339                                 if (com->pc98_8251fifo_enable) {
2340                                     recv_data = inb(I8251F_data);
2341                                     if (tmp & (STS8251F_PE | STS8251F_OE |
2342                                                STS8251F_BD_SD)) {
2343                                         pc98_i8251_or_cmd(com, CMD8251_ER);
2344                                         recv_data = 0;
2345                                     }
2346                                 } else {
2347                                     recv_data = inb(com->data_port);
2348                                     if (tmp & (STS8251_PE | STS8251_OE |
2349                                                STS8251_FE | STS8251_BD_SD)) {
2350                                         pc98_i8251_or_cmd(com, CMD8251_ER);
2351                                         recv_data = 0;
2352                                     }
2353                                 }
2354                         } else if (com->pc98_if_type == COM_IF_RSA98III) {
2355                                 if (!(rsa_buf_status & 0x08))
2356                                         recv_data = 0;
2357                                 else
2358                                         recv_data = inb(com->data_port);
2359                         } else
2360 #endif
2361                         if (!(line_status & LSR_RXRDY))
2362                                 recv_data = 0;
2363                         else
2364                                 recv_data = inb(com->data_port);
2365 #ifdef KDB
2366 #ifdef ALT_BREAK_TO_DEBUGGER
2367                         if (com->unit == comconsole &&
2368                             kdb_alt_break(recv_data, &com->alt_brk_state) != 0)
2369                                 kdb_enter("Break sequence on console");
2370 #endif /* ALT_BREAK_TO_DEBUGGER */
2371 #endif /* KDB */
2372                         if (line_status & (LSR_BI | LSR_FE | LSR_PE)) {
2373                                 /*
2374                                  * Don't store BI if IGNBRK or FE/PE if IGNPAR.
2375                                  * Otherwise, push the work to a higher level
2376                                  * (to handle PARMRK) if we're bypassing.
2377                                  * Otherwise, convert BI/FE and PE+INPCK to 0.
2378                                  *
2379                                  * This makes bypassing work right in the
2380                                  * usual "raw" case (IGNBRK set, and IGNPAR
2381                                  * and INPCK clear).
2382                                  *
2383                                  * Note: BI together with FE/PE means just BI.
2384                                  */
2385                                 if (line_status & LSR_BI) {
2386 #if defined(KDB) && defined(BREAK_TO_DEBUGGER)
2387                                         if (com->unit == comconsole) {
2388                                                 kdb_enter("Line break on console");
2389                                                 goto cont;
2390                                         }
2391 #endif
2392                                         if (com->tp == NULL
2393                                             || com->tp->t_iflag & IGNBRK)
2394                                                 goto cont;
2395                                 } else {
2396                                         if (com->tp == NULL
2397                                             || com->tp->t_iflag & IGNPAR)
2398                                                 goto cont;
2399                                 }
2400                                 if (com->tp->t_state & TS_CAN_BYPASS_L_RINT
2401                                     && (line_status & (LSR_BI | LSR_FE)
2402                                         || com->tp->t_iflag & INPCK))
2403                                         recv_data = 0;
2404                         }
2405                         ++com->bytes_in;
2406                         if (com->tp != NULL &&
2407                             com->tp->t_hotchar != 0 && recv_data == com->tp->t_hotchar)
2408                                 swi_sched(sio_fast_ih, 0);
2409                         ioptr = com->iptr;
2410                         if (ioptr >= com->ibufend)
2411                                 CE_RECORD(com, CE_INTERRUPT_BUF_OVERFLOW);
2412                         else {
2413                                 if (com->tp != NULL && com->tp->t_do_timestamp)
2414                                         microtime(&com->tp->t_timestamp);
2415                                 ++com_events;
2416                                 swi_sched(sio_slow_ih, SWI_DELAY);
2417 #if 0 /* for testing input latency vs efficiency */
2418 if (com->iptr - com->ibuf == 8)
2419         swi_sched(sio_fast_ih, 0);
2420 #endif
2421                                 ioptr[0] = recv_data;
2422                                 ioptr[com->ierroff] = line_status;
2423                                 com->iptr = ++ioptr;
2424                                 if (ioptr == com->ihighwater
2425                                     && com->state & CS_RTS_IFLOW)
2426 #ifdef PC98
2427                                         IS_8251(com->pc98_if_type) ?
2428                                                 com_tiocm_bic(com, TIOCM_RTS) :
2429 #endif
2430                                         outb(com->modem_ctl_port,
2431                                              com->mcr_image &= ~MCR_RTS);
2432                                 if (line_status & LSR_OE)
2433                                         CE_RECORD(com, CE_OVERRUN);
2434                         }
2435 cont:
2436                         if (line_status & LSR_TXRDY
2437                             && com->state >= (CS_BUSY | CS_TTGO | CS_ODEVREADY))
2438                                 goto txrdy;
2439
2440                         /*
2441                          * "& 0x7F" is to avoid the gcc-1.40 generating a slow
2442                          * jump from the top of the loop to here
2443                          */
2444 #ifdef PC98
2445                         if (IS_8251(com->pc98_if_type))
2446                                 goto status_read;
2447                         else
2448 #endif
2449                         line_status = inb(com->line_status_port) & 0x7F;
2450 #ifdef PC98
2451                         if (com->pc98_if_type == COM_IF_RSA98III)
2452                                 rsa_buf_status = inb(com->rsabase + rsa_srr);
2453 #endif /* PC98 */
2454                 }
2455
2456                 /* modem status change? (always check before doing output) */
2457 #ifdef PC98
2458                 if (!IS_8251(com->pc98_if_type)) {
2459 #endif
2460                 modem_status = inb(com->modem_status_port);
2461                 if (modem_status != com->last_modem_status) {
2462                         /*
2463                          * Schedule high level to handle DCD changes.  Note
2464                          * that we don't use the delta bits anywhere.  Some
2465                          * UARTs mess them up, and it's easy to remember the
2466                          * previous bits and calculate the delta.
2467                          */
2468                         com->last_modem_status = modem_status;
2469                         if (!(com->state & CS_CHECKMSR)) {
2470                                 com_events += LOTS_OF_EVENTS;
2471                                 com->state |= CS_CHECKMSR;
2472                                 swi_sched(sio_fast_ih, 0);
2473                         }
2474
2475                         /* handle CTS change immediately for crisp flow ctl */
2476                         if (com->state & CS_CTS_OFLOW) {
2477                                 if (modem_status & MSR_CTS)
2478                                         com->state |= CS_ODEVREADY;
2479                                 else
2480                                         com->state &= ~CS_ODEVREADY;
2481                         }
2482                 }
2483 #ifdef PC98
2484                 }
2485 #endif
2486
2487 txrdy:
2488                 /* output queued and everything ready? */
2489 #ifndef PC98
2490                 if (line_status & LSR_TXRDY
2491                     && com->state >= (CS_BUSY | CS_TTGO | CS_ODEVREADY)) {
2492 #else
2493                 if (((com->pc98_if_type == COM_IF_RSA98III)
2494                      ? (rsa_buf_status & 0x02)
2495                      : (line_status & LSR_TXRDY))
2496                     && com->state >= (CS_BUSY | CS_TTGO | CS_ODEVREADY)) {
2497 #endif
2498 #ifdef PC98
2499                         Port_t  tmp_data_port;
2500                         
2501                         if (IS_8251(com->pc98_if_type) &&
2502                             com->pc98_8251fifo_enable)
2503                                 tmp_data_port = I8251F_data;
2504                         else
2505                                 tmp_data_port = com->data_port;
2506 #endif
2507
2508                         ioptr = com->obufq.l_head;
2509                         if (com->tx_fifo_size > 1 && com->unit != siotsunit) {
2510                                 u_int   ocount;
2511
2512                                 ocount = com->obufq.l_tail - ioptr;
2513 #ifdef PC98
2514                                 if (com->pc98_if_type == COM_IF_RSA98III) {
2515                                   rsa_buf_status = inb(com->rsabase + rsa_srr);
2516                                   rsa_tx_fifo_size = 1024;
2517                                   if (!(rsa_buf_status & 0x01))
2518                                       rsa_tx_fifo_size = 2048;
2519                                   if (ocount > rsa_tx_fifo_size)
2520                                       ocount = rsa_tx_fifo_size;
2521                                 } else
2522 #endif
2523                                 if (ocount > com->tx_fifo_size)
2524                                         ocount = com->tx_fifo_size;
2525                                 com->bytes_out += ocount;
2526                                 do
2527 #ifdef PC98
2528                                         outb(tmp_data_port, *ioptr++);
2529 #else
2530                                         outb(com->data_port, *ioptr++);
2531 #endif
2532                                 while (--ocount != 0);
2533                         } else {
2534 #ifdef PC98
2535                                 outb(tmp_data_port, *ioptr++);
2536 #else
2537                                 outb(com->data_port, *ioptr++);
2538 #endif
2539                                 ++com->bytes_out;
2540                                 if (com->unit == siotsunit
2541                                     && siotso < sizeof siots / sizeof siots[0])
2542                                         nanouptime(&siots[siotso++]);
2543                         }
2544 #ifdef PC98
2545                         if (IS_8251(com->pc98_if_type))
2546                             if (!(pc98_check_i8251_interrupt(com) & IEN_TxFLAG))
2547                                 com_int_Tx_enable(com);
2548 #endif
2549                         com->obufq.l_head = ioptr;
2550                         if (COM_IIR_TXRDYBUG(com->flags))
2551                                 int_ctl_new = int_ctl | IER_ETXRDY;
2552                         if (ioptr >= com->obufq.l_tail) {
2553                                 struct lbq      *qp;
2554
2555                                 qp = com->obufq.l_next;
2556                                 qp->l_queued = FALSE;
2557                                 qp = qp->l_next;
2558                                 if (qp != NULL) {
2559                                         com->obufq.l_head = qp->l_head;
2560                                         com->obufq.l_tail = qp->l_tail;
2561                                         com->obufq.l_next = qp;
2562                                 } else {
2563                                         /* output just completed */
2564                                         if (COM_IIR_TXRDYBUG(com->flags))
2565                                                 int_ctl_new = int_ctl
2566                                                               & ~IER_ETXRDY;
2567                                         com->state &= ~CS_BUSY;
2568 #if defined(PC98)
2569                                         if (IS_8251(com->pc98_if_type) &&
2570                                             pc98_check_i8251_interrupt(com) & IEN_TxFLAG)
2571                                                 com_int_Tx_disable(com);
2572 #endif
2573                                 }
2574                                 if (!(com->state & CS_ODONE)) {
2575                                         com_events += LOTS_OF_EVENTS;
2576                                         com->state |= CS_ODONE;
2577                                         /* handle at high level ASAP */
2578                                         swi_sched(sio_fast_ih, 0);
2579                                 }
2580                         }
2581 #ifdef PC98
2582                         if (COM_IIR_TXRDYBUG(com->flags)
2583                             && int_ctl != int_ctl_new) {
2584                                 if (com->pc98_if_type == COM_IF_RSA98III) {
2585                                     int_ctl_new &= ~(IER_ETXRDY | IER_ERXRDY);
2586                                     outb(com->int_ctl_port, int_ctl_new);
2587                                     outb(com->rsabase + rsa_ier, 0x1d);
2588                                 } else
2589                                     outb(com->int_ctl_port, int_ctl_new);
2590                         }
2591 #else
2592                         if (COM_IIR_TXRDYBUG(com->flags)
2593                             && int_ctl != int_ctl_new)
2594                                 outb(com->int_ctl_port, int_ctl_new);
2595 #endif
2596                 }
2597 #ifdef PC98
2598                 else if (line_status & LSR_TXRDY) {
2599                     if (IS_8251(com->pc98_if_type))
2600                         if (pc98_check_i8251_interrupt(com) & IEN_TxFLAG)
2601                             com_int_Tx_disable(com);
2602                 }
2603                 if (IS_8251(com->pc98_if_type)) {
2604                     if (com->pc98_8251fifo_enable) {
2605                         if ((tmp = inb(I8251F_lsr)) & STS8251F_RxRDY)
2606                             goto more_intr;
2607                     } else {
2608                         if ((tmp = inb(com->sts_port)) & STS8251_RxRDY)
2609                             goto more_intr;
2610                     }
2611                 }
2612 #endif
2613
2614                 /* finished? */
2615 #ifndef COM_MULTIPORT
2616 #ifdef PC98
2617                 if (IS_8251(com->pc98_if_type))
2618                         return;
2619 #endif
2620                 if ((inb(com->int_id_port) & IIR_IMASK) == IIR_NOPEND)
2621 #endif /* COM_MULTIPORT */
2622                         return;
2623         }
2624 }
2625
2626 /* software interrupt handler for SWI_TTY */
2627 static void
2628 siopoll(void *dummy)
2629 {
2630         int             unit;
2631
2632         if (com_events == 0)
2633                 return;
2634 repeat:
2635         for (unit = 0; unit < sio_numunits; ++unit) {
2636                 struct com_s    *com;
2637                 int             incc;
2638                 struct tty      *tp;
2639
2640                 com = com_addr(unit);
2641                 if (com == NULL)
2642                         continue;
2643                 tp = com->tp;
2644                 if (tp == NULL || com->gone) {
2645                         /*
2646                          * Discard any events related to never-opened or
2647                          * going-away devices.
2648                          */
2649                         mtx_lock_spin(&sio_lock);
2650                         incc = com->iptr - com->ibuf;
2651                         com->iptr = com->ibuf;
2652                         if (com->state & CS_CHECKMSR) {
2653                                 incc += LOTS_OF_EVENTS;
2654                                 com->state &= ~CS_CHECKMSR;
2655                         }
2656                         com_events -= incc;
2657                         mtx_unlock_spin(&sio_lock);
2658                         continue;
2659                 }
2660                 if (com->iptr != com->ibuf) {
2661                         mtx_lock_spin(&sio_lock);
2662                         sioinput(com);
2663                         mtx_unlock_spin(&sio_lock);
2664                 }
2665                 if (com->state & CS_CHECKMSR) {
2666                         u_char  delta_modem_status;
2667
2668 #ifdef PC98
2669                         if (!IS_8251(com->pc98_if_type)) {
2670 #endif
2671                         mtx_lock_spin(&sio_lock);
2672                         delta_modem_status = com->last_modem_status
2673                                              ^ com->prev_modem_status;
2674                         com->prev_modem_status = com->last_modem_status;
2675                         com_events -= LOTS_OF_EVENTS;
2676                         com->state &= ~CS_CHECKMSR;
2677                         mtx_unlock_spin(&sio_lock);
2678                         if (delta_modem_status & MSR_DCD)
2679                                 ttyld_modem(tp,
2680                                     com->prev_modem_status & MSR_DCD);
2681 #ifdef PC98
2682                         }
2683 #endif
2684                 }
2685                 if (com->state & CS_ODONE) {
2686                         mtx_lock_spin(&sio_lock);
2687                         com_events -= LOTS_OF_EVENTS;
2688                         com->state &= ~CS_ODONE;
2689                         mtx_unlock_spin(&sio_lock);
2690                         if (!(com->state & CS_BUSY)
2691                             && !(com->extra_state & CSE_BUSYCHECK)) {
2692                                 timeout(siobusycheck, com, hz / 100);
2693                                 com->extra_state |= CSE_BUSYCHECK;
2694                         }
2695                         ttyld_start(tp);
2696                 }
2697                 if (com_events == 0)
2698                         break;
2699         }
2700         if (com_events >= LOTS_OF_EVENTS)
2701                 goto repeat;
2702 }
2703
2704 static void
2705 combreak(tp, sig)
2706         struct tty      *tp;
2707         int             sig;
2708 {
2709         struct com_s    *com;
2710
2711         com = tp->t_sc;
2712
2713 #ifdef PC98
2714         if (sig)
2715                 com_send_break_on(com);
2716         else
2717                 com_send_break_off(com);
2718 #else
2719         if (sig)
2720                 sio_setreg(com, com_cfcr, com->cfcr_image |= CFCR_SBREAK);
2721         else
2722                 sio_setreg(com, com_cfcr, com->cfcr_image &= ~CFCR_SBREAK);
2723 #endif
2724 }
2725
2726 static int
2727 comparam(tp, t)
2728         struct tty      *tp;
2729         struct termios  *t;
2730 {
2731         u_int           cfcr;
2732         int             cflag;
2733         struct com_s    *com;
2734         u_int           divisor;
2735         u_char          dlbh;
2736         u_char          dlbl;
2737         u_char          efr_flowbits;
2738         int             s;
2739 #ifdef PC98
2740         u_char          param = 0;
2741 #endif
2742
2743         com = tp->t_sc;
2744         if (com == NULL)
2745                 return (ENODEV);
2746
2747 #ifdef PC98
2748         cfcr = 0;
2749
2750         if (IS_8251(com->pc98_if_type)) {
2751                 if (pc98_ttspeedtab(com, t->c_ospeed, &divisor) != 0)
2752                         return (EINVAL);
2753         } else {
2754 #endif
2755         /* check requested parameters */
2756         if (t->c_ispeed != (t->c_ospeed != 0 ? t->c_ospeed : tp->t_ospeed))
2757                 return (EINVAL);
2758         divisor = siodivisor(com->rclk, t->c_ispeed);
2759         if (divisor == 0)
2760                 return (EINVAL);
2761 #ifdef PC98
2762         }
2763 #endif
2764
2765         /* parameters are OK, convert them to the com struct and the device */
2766         s = spltty();
2767 #ifdef PC98
2768         if (IS_8251(com->pc98_if_type)) {
2769                 if (t->c_ospeed == 0)
2770                         com_tiocm_bic(com, TIOCM_DTR|TIOCM_RTS|TIOCM_LE);
2771                 else
2772                         com_tiocm_bis(com, TIOCM_DTR|TIOCM_RTS|TIOCM_LE);
2773         } else
2774 #endif
2775         if (t->c_ospeed == 0)
2776                 (void)commodem(tp, 0, SER_DTR); /* hang up line */
2777         else
2778                 (void)commodem(tp, SER_DTR, 0);
2779         cflag = t->c_cflag;
2780 #ifdef PC98
2781         if (!IS_8251(com->pc98_if_type)) {
2782 #endif
2783         switch (cflag & CSIZE) {
2784         case CS5:
2785                 cfcr = CFCR_5BITS;
2786                 break;
2787         case CS6:
2788                 cfcr = CFCR_6BITS;
2789                 break;
2790         case CS7:
2791                 cfcr = CFCR_7BITS;
2792                 break;
2793         default:
2794                 cfcr = CFCR_8BITS;
2795                 break;
2796         }
2797         if (cflag & PARENB) {
2798                 cfcr |= CFCR_PENAB;
2799                 if (!(cflag & PARODD))
2800                         cfcr |= CFCR_PEVEN;
2801         }
2802         if (cflag & CSTOPB)
2803                 cfcr |= CFCR_STOPB;
2804
2805         if (com->hasfifo) {
2806                 /*
2807                  * Use a fifo trigger level low enough so that the input
2808                  * latency from the fifo is less than about 16 msec and
2809                  * the total latency is less than about 30 msec.  These
2810                  * latencies are reasonable for humans.  Serial comms
2811                  * protocols shouldn't expect anything better since modem
2812                  * latencies are larger.
2813                  *
2814                  * The fifo trigger level cannot be set at RX_HIGH for high
2815                  * speed connections without further work on reducing 
2816                  * interrupt disablement times in other parts of the system,
2817                  * without producing silo overflow errors.
2818                  */
2819                 com->fifo_image = com->unit == siotsunit ? 0
2820                                   : t->c_ispeed <= 4800
2821                                   ? FIFO_ENABLE : FIFO_ENABLE | FIFO_RX_MEDH;
2822 #ifdef COM_ESP
2823                 /*
2824                  * The Hayes ESP card needs the fifo DMA mode bit set
2825                  * in compatibility mode.  If not, it will interrupt
2826                  * for each character received.
2827                  */
2828                 if (com->esp)
2829                         com->fifo_image |= FIFO_DMA_MODE;
2830 #endif
2831                 sio_setreg(com, com_fifo, com->fifo_image);
2832         }
2833 #ifdef PC98
2834         }
2835 #endif
2836
2837         /*
2838          * This returns with interrupts disabled so that we can complete
2839          * the speed change atomically.  Keeping interrupts disabled is
2840          * especially important while com_data is hidden.
2841          */
2842         (void) siosetwater(com, t->c_ispeed);
2843
2844 #ifdef PC98
2845         if (IS_8251(com->pc98_if_type))
2846                 com_cflag_and_speed_set(com, cflag, t->c_ospeed);
2847         else {
2848 #endif
2849         sio_setreg(com, com_cfcr, cfcr | CFCR_DLAB);
2850         /*
2851          * Only set the divisor registers if they would change, since on
2852          * some 16550 incompatibles (UMC8669F), setting them while input
2853          * is arriving loses sync until data stops arriving.
2854          */
2855         dlbl = divisor & 0xFF;
2856         if (sio_getreg(com, com_dlbl) != dlbl)
2857                 sio_setreg(com, com_dlbl, dlbl);
2858         dlbh = divisor >> 8;
2859         if (sio_getreg(com, com_dlbh) != dlbh)
2860                 sio_setreg(com, com_dlbh, dlbh);
2861 #ifdef PC98
2862         }
2863 #endif
2864
2865         efr_flowbits = 0;
2866
2867         if (cflag & CRTS_IFLOW) {
2868                 com->state |= CS_RTS_IFLOW;
2869                 efr_flowbits |= EFR_AUTORTS;
2870                 /*
2871                  * If CS_RTS_IFLOW just changed from off to on, the change
2872                  * needs to be propagated to MCR_RTS.  This isn't urgent,
2873                  * so do it later by calling comstart() instead of repeating
2874                  * a lot of code from comstart() here.
2875                  */
2876         } else if (com->state & CS_RTS_IFLOW) {
2877                 com->state &= ~CS_RTS_IFLOW;
2878                 /*
2879                  * CS_RTS_IFLOW just changed from on to off.  Force MCR_RTS
2880                  * on here, since comstart() won't do it later.
2881                  */
2882 #ifdef PC98
2883                 if (IS_8251(com->pc98_if_type))
2884                         com_tiocm_bis(com, TIOCM_RTS);
2885                 else
2886                         outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
2887 #else
2888                 outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
2889 #endif
2890         }
2891
2892         /*
2893          * Set up state to handle output flow control.
2894          * XXX - worth handling MDMBUF (DCD) flow control at the lowest level?
2895          * Now has 10+ msec latency, while CTS flow has 50- usec latency.
2896          */
2897         com->state |= CS_ODEVREADY;
2898         com->state &= ~CS_CTS_OFLOW;
2899 #ifdef PC98
2900         if (com->pc98_if_type == COM_IF_RSA98III) {
2901                 param = inb(com->rsabase + rsa_msr);
2902                 outb(com->rsabase + rsa_msr, param & 0x14);
2903         }
2904 #endif
2905         if (cflag & CCTS_OFLOW) {
2906                 com->state |= CS_CTS_OFLOW;
2907                 efr_flowbits |= EFR_AUTOCTS;
2908 #ifdef PC98
2909                 if (IS_8251(com->pc98_if_type)) {
2910                         if (!(pc98_get_modem_status(com) & TIOCM_CTS))
2911                                 com->state &= ~CS_ODEVREADY;
2912                 } else if (com->pc98_if_type == COM_IF_RSA98III) {
2913                         /* Set automatic flow control mode */
2914                         outb(com->rsabase + rsa_msr, param | 0x08);
2915                 } else
2916 #endif
2917                 if (!(com->last_modem_status & MSR_CTS))
2918                         com->state &= ~CS_ODEVREADY;
2919         }
2920
2921 #ifdef PC98
2922         if (!IS_8251(com->pc98_if_type))
2923                 sio_setreg(com, com_cfcr, com->cfcr_image = cfcr);
2924 #else
2925         if (com->st16650a) {
2926                 sio_setreg(com, com_lcr, LCR_EFR_ENABLE);
2927                 sio_setreg(com, com_efr,
2928                            (sio_getreg(com, com_efr)
2929                             & ~(EFR_AUTOCTS | EFR_AUTORTS)) | efr_flowbits);
2930         }
2931         sio_setreg(com, com_cfcr, com->cfcr_image = cfcr);
2932 #endif
2933
2934         /* XXX shouldn't call functions while intrs are disabled. */
2935         ttyldoptim(tp);
2936
2937         mtx_unlock_spin(&sio_lock);
2938         splx(s);
2939         comstart(tp);
2940         if (com->ibufold != NULL) {
2941                 free(com->ibufold, M_DEVBUF);
2942                 com->ibufold = NULL;
2943         }
2944         return (0);
2945 }
2946
2947 /*
2948  * This function must be called with the sio_lock mutex released and will
2949  * return with it obtained.
2950  */
2951 static int
2952 siosetwater(com, speed)
2953         struct com_s    *com;
2954         speed_t         speed;
2955 {
2956         int             cp4ticks;
2957         u_char          *ibuf;
2958         int             ibufsize;
2959         struct tty      *tp;
2960
2961         /*
2962          * Make the buffer size large enough to handle a softtty interrupt
2963          * latency of about 2 ticks without loss of throughput or data
2964          * (about 3 ticks if input flow control is not used or not honoured,
2965          * but a bit less for CS5-CS7 modes).
2966          */
2967         cp4ticks = speed / 10 / hz * 4;
2968         for (ibufsize = 128; ibufsize < cp4ticks;)
2969                 ibufsize <<= 1;
2970 #ifdef PC98
2971         if (com->pc98_if_type == COM_IF_RSA98III)
2972                 ibufsize = 2048;
2973 #endif
2974         if (ibufsize == com->ibufsize) {
2975                 mtx_lock_spin(&sio_lock);
2976                 return (0);
2977         }
2978
2979         /*
2980          * Allocate input buffer.  The extra factor of 2 in the size is
2981          * to allow for an error byte for each input byte.
2982          */
2983         ibuf = malloc(2 * ibufsize, M_DEVBUF, M_NOWAIT);
2984         if (ibuf == NULL) {
2985                 mtx_lock_spin(&sio_lock);
2986                 return (ENOMEM);
2987         }
2988
2989         /* Initialize non-critical variables. */
2990         com->ibufold = com->ibuf;
2991         com->ibufsize = ibufsize;
2992         tp = com->tp;
2993         if (tp != NULL) {
2994                 tp->t_ififosize = 2 * ibufsize;
2995                 tp->t_ispeedwat = (speed_t)-1;
2996                 tp->t_ospeedwat = (speed_t)-1;
2997         }
2998
2999         /*
3000          * Read current input buffer, if any.  Continue with interrupts
3001          * disabled.
3002          */
3003         mtx_lock_spin(&sio_lock);
3004         if (com->iptr != com->ibuf)
3005                 sioinput(com);
3006
3007         /*-
3008          * Initialize critical variables, including input buffer watermarks.
3009          * The external device is asked to stop sending when the buffer
3010          * exactly reaches high water, or when the high level requests it.
3011          * The high level is notified immediately (rather than at a later
3012          * clock tick) when this watermark is reached.
3013          * The buffer size is chosen so the watermark should almost never
3014          * be reached.
3015          * The low watermark is invisibly 0 since the buffer is always
3016          * emptied all at once.
3017          */
3018         com->iptr = com->ibuf = ibuf;
3019         com->ibufend = ibuf + ibufsize;
3020         com->ierroff = ibufsize;
3021         com->ihighwater = ibuf + 3 * ibufsize / 4;
3022         return (0);
3023 }
3024
3025 static void
3026 comstart(tp)
3027         struct tty      *tp;
3028 {
3029         struct com_s    *com;
3030         int             s;
3031
3032         com = tp->t_sc;
3033         if (com == NULL)
3034                 return;
3035         s = spltty();
3036         mtx_lock_spin(&sio_lock);
3037         if (tp->t_state & TS_TTSTOP)
3038                 com->state &= ~CS_TTGO;
3039         else
3040                 com->state |= CS_TTGO;
3041         if (tp->t_state & TS_TBLOCK) {
3042 #ifdef PC98
3043                 if (IS_8251(com->pc98_if_type)) {
3044                     if ((com_tiocm_get(com) & TIOCM_RTS) &&
3045                         (com->state & CS_RTS_IFLOW))
3046                         com_tiocm_bic(com, TIOCM_RTS);
3047                 } else {
3048                     if ((com->mcr_image & MCR_RTS) &&
3049                         (com->state & CS_RTS_IFLOW))
3050                         outb(com->modem_ctl_port, com->mcr_image &= ~MCR_RTS);
3051                 }
3052 #else
3053                 if (com->mcr_image & MCR_RTS && com->state & CS_RTS_IFLOW)
3054                         outb(com->modem_ctl_port, com->mcr_image &= ~MCR_RTS);
3055 #endif
3056         } else {
3057 #ifdef PC98
3058                 if (IS_8251(com->pc98_if_type)) {
3059                     if (!(com_tiocm_get(com) & TIOCM_RTS) &&
3060                         com->iptr < com->ihighwater &&
3061                         com->state & CS_RTS_IFLOW)
3062                         com_tiocm_bis(com, TIOCM_RTS);
3063                 } else {
3064                     if (!(com->mcr_image & MCR_RTS) &&
3065                         com->iptr < com->ihighwater &&
3066                         com->state & CS_RTS_IFLOW)
3067                         outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
3068                 }
3069 #else
3070                 if (!(com->mcr_image & MCR_RTS) && com->iptr < com->ihighwater
3071                     && com->state & CS_RTS_IFLOW)
3072                         outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
3073 #endif
3074         }
3075         mtx_unlock_spin(&sio_lock);
3076         if (tp->t_state & (TS_TIMEOUT | TS_TTSTOP)) {
3077                 ttwwakeup(tp);
3078                 splx(s);
3079                 return;
3080         }
3081         if (tp->t_outq.c_cc != 0) {
3082                 struct lbq      *qp;
3083                 struct lbq      *next;
3084
3085                 if (!com->obufs[0].l_queued) {
3086                         com->obufs[0].l_tail
3087                             = com->obuf1 + q_to_b(&tp->t_outq, com->obuf1,
3088 #ifdef PC98
3089                                                   com->obufsize);
3090 #else
3091                                                   sizeof com->obuf1);
3092 #endif
3093                         com->obufs[0].l_next = NULL;
3094                         com->obufs[0].l_queued = TRUE;
3095                         mtx_lock_spin(&sio_lock);
3096                         if (com->state & CS_BUSY) {
3097                                 qp = com->obufq.l_next;
3098                                 while ((next = qp->l_next) != NULL)
3099                                         qp = next;
3100                                 qp->l_next = &com->obufs[0];
3101                         } else {
3102                                 com->obufq.l_head = com->obufs[0].l_head;
3103                                 com->obufq.l_tail = com->obufs[0].l_tail;
3104                                 com->obufq.l_next = &com->obufs[0];
3105                                 com->state |= CS_BUSY;
3106                         }
3107                         mtx_unlock_spin(&sio_lock);
3108                 }
3109                 if (tp->t_outq.c_cc != 0 && !com->obufs[1].l_queued) {
3110                         com->obufs[1].l_tail
3111                             = com->obuf2 + q_to_b(&tp->t_outq, com->obuf2,
3112 #ifdef PC98
3113                                                   com->obufsize);
3114 #else
3115                                                   sizeof com->obuf2);
3116 #endif
3117                         com->obufs[1].l_next = NULL;
3118                         com->obufs[1].l_queued = TRUE;
3119                         mtx_lock_spin(&sio_lock);
3120                         if (com->state & CS_BUSY) {
3121                                 qp = com->obufq.l_next;
3122                                 while ((next = qp->l_next) != NULL)
3123                                         qp = next;
3124                                 qp->l_next = &com->obufs[1];
3125                         } else {
3126                                 com->obufq.l_head = com->obufs[1].l_head;
3127                                 com->obufq.l_tail = com->obufs[1].l_tail;
3128                                 com->obufq.l_next = &com->obufs[1];
3129                                 com->state |= CS_BUSY;
3130                         }
3131                         mtx_unlock_spin(&sio_lock);
3132                 }
3133                 tp->t_state |= TS_BUSY;
3134         }
3135         mtx_lock_spin(&sio_lock);
3136         if (com->state >= (CS_BUSY | CS_TTGO))
3137                 siointr1(com);  /* fake interrupt to start output */
3138         mtx_unlock_spin(&sio_lock);
3139         ttwwakeup(tp);
3140         splx(s);
3141 }
3142
3143 static void
3144 comstop(tp, rw)
3145         struct tty      *tp;
3146         int             rw;
3147 {
3148         struct com_s    *com;
3149 #ifdef PC98
3150         int             rsa98_tmp  = 0;
3151 #endif
3152
3153         com = tp->t_sc;
3154         if (com == NULL || com->gone)
3155                 return;
3156         mtx_lock_spin(&sio_lock);
3157         if (rw & FWRITE) {
3158 #ifdef PC98
3159                 if (!IS_8251(com->pc98_if_type)) {
3160 #endif
3161                 if (com->hasfifo)
3162 #ifdef COM_ESP
3163                     /* XXX avoid h/w bug. */
3164                     if (!com->esp)
3165 #endif
3166                         sio_setreg(com, com_fifo,
3167                                    FIFO_XMT_RST | com->fifo_image);
3168 #ifdef PC98
3169                 if (com->pc98_if_type == COM_IF_RSA98III)
3170                     for (rsa98_tmp = 0; rsa98_tmp < 2048; rsa98_tmp++)
3171                         sio_setreg(com, com_fifo,
3172                                    FIFO_XMT_RST | com->fifo_image);
3173                 }
3174 #endif
3175                 com->obufs[0].l_queued = FALSE;
3176                 com->obufs[1].l_queued = FALSE;
3177                 if (com->state & CS_ODONE)
3178                         com_events -= LOTS_OF_EVENTS;
3179                 com->state &= ~(CS_ODONE | CS_BUSY);
3180                 com->tp->t_state &= ~TS_BUSY;
3181         }
3182         if (rw & FREAD) {
3183 #ifdef PC98
3184                 if (!IS_8251(com->pc98_if_type)) {
3185                     if (com->pc98_if_type == COM_IF_RSA98III)
3186                         for (rsa98_tmp = 0; rsa98_tmp < 2048; rsa98_tmp++)
3187                             sio_getreg(com, com_data);
3188 #endif
3189                 if (com->hasfifo)
3190 #ifdef COM_ESP
3191                     /* XXX avoid h/w bug. */
3192                     if (!com->esp)
3193 #endif
3194                         sio_setreg(com, com_fifo,
3195                                    FIFO_RCV_RST | com->fifo_image);
3196 #ifdef PC98
3197                 }
3198 #endif
3199                 com_events -= (com->iptr - com->ibuf);
3200                 com->iptr = com->ibuf;
3201         }
3202         mtx_unlock_spin(&sio_lock);
3203         comstart(tp);
3204 }
3205
3206 static int
3207 commodem(struct tty *tp, int sigon, int sigoff)
3208 {
3209         struct com_s    *com;
3210         int     bitand, bitor, msr;
3211 #ifdef PC98
3212         int     clr, set;
3213 #endif
3214
3215         com = tp->t_sc;
3216         if (com->gone)
3217                 return(0);
3218         if (sigon != 0 || sigoff != 0) {
3219 #ifdef PC98
3220                 if (IS_8251(com->pc98_if_type)) {
3221                         bitand = bitor = 0;     
3222                         clr = set = 0;
3223                         if (sigoff & SER_DTR) {
3224                                 bitand |= TIOCM_DTR;
3225                                 clr |= CMD8251_DTR;
3226                         }
3227                         if (sigoff & SER_RTS) {
3228                                 bitand |= TIOCM_RTS;
3229                                 clr |= CMD8251_RxEN | CMD8251_RTS;
3230                         }
3231                         if (sigon & SER_DTR) {
3232                                 bitor |= TIOCM_DTR;
3233                                 set |= CMD8251_TxEN | CMD8251_RxEN |
3234                                         CMD8251_DTR;
3235                         }
3236                         if (sigon & SER_RTS) {
3237                                 bitor |= TIOCM_RTS;
3238                                 set |= CMD8251_TxEN | CMD8251_RxEN |
3239                                         CMD8251_RTS;
3240                         }
3241                         bitand = ~bitand;
3242                         mtx_lock_spin(&sio_lock);
3243                         com->pc98_prev_modem_status &= bitand;
3244                         com->pc98_prev_modem_status |= bitor;
3245                         pc98_i8251_clear_or_cmd(com, clr, set);
3246                         mtx_unlock_spin(&sio_lock);
3247                         return (0);
3248                 } else {
3249 #endif
3250                 bitand = bitor = 0;
3251                 if (sigoff & SER_DTR)
3252                         bitand |= MCR_DTR;
3253                 if (sigoff & SER_RTS)
3254                         bitand |= MCR_RTS;
3255                 if (sigon & SER_DTR)
3256                         bitor |= MCR_DTR;
3257                 if (sigon & SER_RTS)
3258                         bitor |= MCR_RTS;
3259                 bitand = ~bitand;
3260                 mtx_lock_spin(&sio_lock);
3261                 com->mcr_image &= bitand;
3262                 com->mcr_image |= bitor;
3263                 outb(com->modem_ctl_port, com->mcr_image);
3264                 mtx_unlock_spin(&sio_lock);
3265                 return (0);
3266 #ifdef PC98
3267                 }
3268 #endif
3269         } else {
3270 #ifdef PC98
3271                 if (IS_8251(com->pc98_if_type))
3272                         return (com_tiocm_get(com));
3273                 else {
3274 #endif
3275                 bitor = 0;
3276                 if (com->mcr_image & MCR_DTR)
3277                         bitor |= SER_DTR;
3278                 if (com->mcr_image & MCR_RTS)
3279                         bitor |= SER_RTS;
3280                 msr = com->prev_modem_status;
3281                 if (msr & MSR_CTS)
3282                         bitor |= SER_CTS;
3283                 if (msr & MSR_DCD)
3284                         bitor |= SER_DCD;
3285                 if (msr & MSR_DSR)
3286                         bitor |= SER_DSR;
3287                 if (msr & MSR_DSR)
3288                         bitor |= SER_DSR;
3289                 if (msr & (MSR_RI | MSR_TERI))
3290                         bitor |= SER_RI;
3291                 return (bitor);
3292 #ifdef PC98
3293                 }
3294 #endif
3295         }
3296 }
3297
3298 static void
3299 siosettimeout()
3300 {
3301         struct com_s    *com;
3302         bool_t          someopen;
3303         int             unit;
3304
3305         /*
3306          * Set our timeout period to 1 second if no polled devices are open.
3307          * Otherwise set it to max(1/200, 1/hz).
3308          * Enable timeouts iff some device is open.
3309          */
3310         untimeout(comwakeup, (void *)NULL, sio_timeout_handle);
3311         sio_timeout = hz;
3312         someopen = FALSE;
3313         for (unit = 0; unit < sio_numunits; ++unit) {
3314                 com = com_addr(unit);
3315                 if (com != NULL && com->tp != NULL
3316                     && com->tp->t_state & TS_ISOPEN && !com->gone) {
3317                         someopen = TRUE;
3318                         if (com->poll || com->poll_output) {
3319                                 sio_timeout = hz > 200 ? hz / 200 : 1;
3320                                 break;
3321                         }
3322                 }
3323         }
3324         if (someopen) {
3325                 sio_timeouts_until_log = hz / sio_timeout;
3326                 sio_timeout_handle = timeout(comwakeup, (void *)NULL,
3327                                              sio_timeout);
3328         } else {
3329                 /* Flush error messages, if any. */
3330                 sio_timeouts_until_log = 1;
3331                 comwakeup((void *)NULL);
3332                 untimeout(comwakeup, (void *)NULL, sio_timeout_handle);
3333         }
3334 }
3335
3336 static void
3337 comwakeup(chan)
3338         void    *chan;
3339 {
3340         struct com_s    *com;
3341         int             unit;
3342
3343         sio_timeout_handle = timeout(comwakeup, (void *)NULL, sio_timeout);
3344
3345         /*
3346          * Recover from lost output interrupts.
3347          * Poll any lines that don't use interrupts.
3348          */
3349         for (unit = 0; unit < sio_numunits; ++unit) {
3350                 com = com_addr(unit);
3351                 if (com != NULL && !com->gone
3352                     && (com->state >= (CS_BUSY | CS_TTGO) || com->poll)) {
3353                         mtx_lock_spin(&sio_lock);
3354                         siointr1(com);
3355                         mtx_unlock_spin(&sio_lock);
3356                 }
3357         }
3358
3359         /*
3360          * Check for and log errors, but not too often.
3361          */
3362         if (--sio_timeouts_until_log > 0)
3363                 return;
3364         sio_timeouts_until_log = hz / sio_timeout;
3365         for (unit = 0; unit < sio_numunits; ++unit) {
3366                 int     errnum;
3367
3368                 com = com_addr(unit);
3369                 if (com == NULL)
3370                         continue;
3371                 if (com->gone)
3372                         continue;
3373                 for (errnum = 0; errnum < CE_NTYPES; ++errnum) {
3374                         u_int   delta;
3375                         u_long  total;
3376
3377                         mtx_lock_spin(&sio_lock);
3378                         delta = com->delta_error_counts[errnum];
3379                         com->delta_error_counts[errnum] = 0;
3380                         mtx_unlock_spin(&sio_lock);
3381                         if (delta == 0)
3382                                 continue;
3383                         total = com->error_counts[errnum] += delta;
3384                         log(LOG_ERR, "sio%d: %u more %s%s (total %lu)\n",
3385                             unit, delta, error_desc[errnum],
3386                             delta == 1 ? "" : "s", total);
3387                 }
3388         }
3389 }
3390
3391 #ifdef PC98
3392 /* commint is called when modem control line changes */
3393 static void
3394 commint(struct cdev *dev)
3395 {
3396         register struct tty *tp;
3397         int     stat,delta;
3398         struct com_s *com;
3399
3400         com = dev->si_drv1;
3401         tp = com->tp;
3402
3403         stat = com_tiocm_get(com);
3404         delta = com_tiocm_get_delta(com);
3405
3406         if (com->state & CS_CTS_OFLOW) {
3407                 if (stat & TIOCM_CTS)
3408                         com->state |= CS_ODEVREADY;
3409                 else
3410                         com->state &= ~CS_ODEVREADY;
3411         }
3412         if ((delta & TIOCM_CAR) && (ISCALLOUT(dev)) == 0) {
3413             if (stat & TIOCM_CAR )
3414                 (void)ttyld_modem(tp, 1);
3415             else if (ttyld_modem(tp, 0) == 0) {
3416                 /* negate DTR, RTS */
3417                 com_tiocm_bic(com, (tp->t_cflag & HUPCL) ?
3418                                 TIOCM_DTR|TIOCM_RTS|TIOCM_LE : TIOCM_LE );
3419                 /* disable IENABLE */
3420                 com_int_TxRx_disable( com );
3421             }
3422         }
3423 }
3424 #endif
3425
3426 /*
3427  * Following are all routines needed for SIO to act as console
3428  */
3429 struct siocnstate {
3430         u_char  dlbl;
3431         u_char  dlbh;
3432         u_char  ier;
3433         u_char  cfcr;
3434         u_char  mcr;
3435 };
3436
3437 /*
3438  * This is a function in order to not replicate "ttyd%d" more
3439  * places than absolutely necessary.
3440  */
3441 static void
3442 siocnset(struct consdev *cd, int unit)
3443 {
3444
3445         cd->cn_unit = unit;
3446         sprintf(cd->cn_name, "ttyd%d", unit);
3447 }
3448
3449 static speed_t siocngetspeed(Port_t, u_long rclk);
3450 static void siocnclose(struct siocnstate *sp, Port_t iobase);
3451 static void siocnopen(struct siocnstate *sp, Port_t iobase, int speed);
3452 static void siocntxwait(Port_t iobase);
3453
3454 static cn_probe_t siocnprobe;
3455 static cn_init_t siocninit;
3456 static cn_term_t siocnterm;
3457 static cn_checkc_t siocncheckc;
3458 static cn_getc_t siocngetc;
3459 static cn_putc_t siocnputc;
3460
3461 CONS_DRIVER(sio, siocnprobe, siocninit, siocnterm, siocngetc, siocncheckc,
3462             siocnputc, NULL);
3463
3464 static void
3465 siocntxwait(iobase)
3466         Port_t  iobase;
3467 {
3468         int     timo;
3469
3470         /*
3471          * Wait for any pending transmission to finish.  Required to avoid
3472          * the UART lockup bug when the speed is changed, and for normal
3473          * transmits.
3474          */
3475         timo = 100000;
3476         while ((inb(iobase + com_lsr) & (LSR_TSRE | LSR_TXRDY))
3477                != (LSR_TSRE | LSR_TXRDY) && --timo != 0)
3478                 ;
3479 }
3480
3481 /*
3482  * Read the serial port specified and try to figure out what speed
3483  * it's currently running at.  We're assuming the serial port has
3484  * been initialized and is basicly idle.  This routine is only intended
3485  * to be run at system startup.
3486  *
3487  * If the value read from the serial port doesn't make sense, return 0.
3488  */
3489
3490 static speed_t
3491 siocngetspeed(iobase, rclk)
3492         Port_t  iobase;
3493         u_long  rclk;
3494 {
3495         u_int   divisor;
3496         u_char  dlbh;
3497         u_char  dlbl;
3498         u_char  cfcr;
3499
3500         cfcr = inb(iobase + com_cfcr);
3501         outb(iobase + com_cfcr, CFCR_DLAB | cfcr);
3502
3503         dlbl = inb(iobase + com_dlbl);
3504         dlbh = inb(iobase + com_dlbh);
3505
3506         outb(iobase + com_cfcr, cfcr);
3507
3508         divisor = dlbh << 8 | dlbl;
3509
3510         /* XXX there should be more sanity checking. */
3511         if (divisor == 0)
3512                 return (CONSPEED);
3513         return (rclk / (16UL * divisor));
3514 }
3515
3516 static void
3517 siocnopen(sp, iobase, speed)
3518         struct siocnstate       *sp;
3519         Port_t                  iobase;
3520         int                     speed;
3521 {
3522         u_int   divisor;
3523         u_char  dlbh;
3524         u_char  dlbl;
3525
3526         /*
3527          * Save all the device control registers except the fifo register
3528          * and set our default ones (cs8 -parenb speed=comdefaultrate).
3529          * We can't save the fifo register since it is read-only.
3530          */
3531         sp->ier = inb(iobase + com_ier);
3532         outb(iobase + com_ier, 0);      /* spltty() doesn't stop siointr() */
3533         siocntxwait(iobase);
3534         sp->cfcr = inb(iobase + com_cfcr);
3535         outb(iobase + com_cfcr, CFCR_DLAB | CFCR_8BITS);
3536         sp->dlbl = inb(iobase + com_dlbl);
3537         sp->dlbh = inb(iobase + com_dlbh);
3538         /*
3539          * Only set the divisor registers if they would change, since on
3540          * some 16550 incompatibles (Startech), setting them clears the
3541          * data input register.  This also reduces the effects of the
3542          * UMC8669F bug.
3543          */
3544         divisor = siodivisor(comdefaultrclk, speed);
3545         dlbl = divisor & 0xFF;
3546         if (sp->dlbl != dlbl)
3547                 outb(iobase + com_dlbl, dlbl);
3548         dlbh = divisor >> 8;
3549         if (sp->dlbh != dlbh)
3550                 outb(iobase + com_dlbh, dlbh);
3551         outb(iobase + com_cfcr, CFCR_8BITS);
3552         sp->mcr = inb(iobase + com_mcr);
3553         /*
3554          * We don't want interrupts, but must be careful not to "disable"
3555          * them by clearing the MCR_IENABLE bit, since that might cause
3556          * an interrupt by floating the IRQ line.
3557          */
3558         outb(iobase + com_mcr, (sp->mcr & MCR_IENABLE) | MCR_DTR | MCR_RTS);
3559 }
3560
3561 static void
3562 siocnclose(sp, iobase)
3563         struct siocnstate       *sp;
3564         Port_t                  iobase;
3565 {
3566         /*
3567          * Restore the device control registers.
3568          */
3569         siocntxwait(iobase);
3570         outb(iobase + com_cfcr, CFCR_DLAB | CFCR_8BITS);
3571         if (sp->dlbl != inb(iobase + com_dlbl))
3572                 outb(iobase + com_dlbl, sp->dlbl);
3573         if (sp->dlbh != inb(iobase + com_dlbh))
3574                 outb(iobase + com_dlbh, sp->dlbh);
3575         outb(iobase + com_cfcr, sp->cfcr);
3576         /*
3577          * XXX damp oscillations of MCR_DTR and MCR_RTS by not restoring them.
3578          */
3579         outb(iobase + com_mcr, sp->mcr | MCR_DTR | MCR_RTS);
3580         outb(iobase + com_ier, sp->ier);
3581 }
3582
3583 static void
3584 siocnprobe(cp)
3585         struct consdev  *cp;
3586 {
3587         speed_t                 boot_speed;
3588         u_char                  cfcr;
3589         u_int                   divisor;
3590         int                     s, unit;
3591         struct siocnstate       sp;
3592
3593         /*
3594          * Find our first enabled console, if any.  If it is a high-level
3595          * console device, then initialize it and return successfully.
3596          * If it is a low-level console device, then initialize it and
3597          * return unsuccessfully.  It must be initialized in both cases
3598          * for early use by console drivers and debuggers.  Initializing
3599          * the hardware is not necessary in all cases, since the i/o
3600          * routines initialize it on the fly, but it is necessary if
3601          * input might arrive while the hardware is switched back to an
3602          * uninitialized state.  We can't handle multiple console devices
3603          * yet because our low-level routines don't take a device arg.
3604          * We trust the user to set the console flags properly so that we
3605          * don't need to probe.
3606          */
3607         cp->cn_pri = CN_DEAD;
3608
3609         for (unit = 0; unit < 16; unit++) { /* XXX need to know how many */
3610                 int flags;
3611
3612                 if (resource_disabled("sio", unit))
3613                         continue;
3614                 if (resource_int_value("sio", unit, "flags", &flags))
3615                         continue;
3616                 if (COM_CONSOLE(flags) || COM_DEBUGGER(flags)) {
3617                         int port;
3618                         Port_t iobase;
3619
3620                         if (resource_int_value("sio", unit, "port", &port))
3621                                 continue;
3622                         iobase = port;
3623                         s = spltty();
3624                         if (boothowto & RB_SERIAL) {
3625                                 boot_speed =
3626                                     siocngetspeed(iobase, comdefaultrclk);
3627                                 if (boot_speed)
3628                                         comdefaultrate = boot_speed;
3629                         }
3630
3631                         /*
3632                          * Initialize the divisor latch.  We can't rely on
3633                          * siocnopen() to do this the first time, since it 
3634                          * avoids writing to the latch if the latch appears
3635                          * to have the correct value.  Also, if we didn't
3636                          * just read the speed from the hardware, then we
3637                          * need to set the speed in hardware so that
3638                          * switching it later is null.
3639                          */
3640                         cfcr = inb(iobase + com_cfcr);
3641                         outb(iobase + com_cfcr, CFCR_DLAB | cfcr);
3642                         divisor = siodivisor(comdefaultrclk, comdefaultrate);
3643                         outb(iobase + com_dlbl, divisor & 0xff);
3644                         outb(iobase + com_dlbh, divisor >> 8);
3645                         outb(iobase + com_cfcr, cfcr);
3646
3647                         siocnopen(&sp, iobase, comdefaultrate);
3648
3649                         splx(s);
3650                         if (COM_CONSOLE(flags) && !COM_LLCONSOLE(flags)) {
3651                                 siocnset(cp, unit);
3652                                 cp->cn_pri = COM_FORCECONSOLE(flags)
3653                                              || boothowto & RB_SERIAL
3654                                              ? CN_REMOTE : CN_NORMAL;
3655                                 siocniobase = iobase;
3656                                 siocnunit = unit;
3657                         }
3658 #ifdef GDB
3659                         if (COM_DEBUGGER(flags))
3660                                 siogdbiobase = iobase;
3661 #endif
3662                 }
3663         }
3664 }
3665
3666 static void
3667 siocninit(cp)
3668         struct consdev  *cp;
3669 {
3670         comconsole = cp->cn_unit;
3671 }
3672
3673 static void
3674 siocnterm(cp)
3675         struct consdev  *cp;
3676 {
3677         comconsole = -1;
3678 }
3679
3680 static int
3681 siocncheckc(struct consdev *cd)
3682 {
3683         int     c;
3684         Port_t  iobase;
3685         int     s;
3686         struct siocnstate       sp;
3687         speed_t speed;
3688
3689         if (cd != NULL && cd->cn_unit == siocnunit) {
3690                 iobase = siocniobase;
3691                 speed = comdefaultrate;
3692         } else {
3693 #ifdef GDB
3694                 iobase = siogdbiobase;
3695                 speed = gdbdefaultrate;
3696 #else
3697                 return (-1);
3698 #endif
3699         }
3700         s = spltty();
3701         siocnopen(&sp, iobase, speed);
3702         if (inb(iobase + com_lsr) & LSR_RXRDY)
3703                 c = inb(iobase + com_data);
3704         else
3705                 c = -1;
3706         siocnclose(&sp, iobase);
3707         splx(s);
3708         return (c);
3709 }
3710
3711 static int
3712 siocngetc(struct consdev *cd)
3713 {
3714         int     c;
3715         Port_t  iobase;
3716         int     s;
3717         struct siocnstate       sp;
3718         speed_t speed;
3719
3720         if (cd != NULL && cd->cn_unit == siocnunit) {
3721                 iobase = siocniobase;
3722                 speed = comdefaultrate;
3723         } else {
3724 #ifdef GDB
3725                 iobase = siogdbiobase;
3726                 speed = gdbdefaultrate;
3727 #else
3728                 return (-1);
3729 #endif
3730         }
3731         s = spltty();
3732         siocnopen(&sp, iobase, speed);
3733         while (!(inb(iobase + com_lsr) & LSR_RXRDY))
3734                 ;
3735         c = inb(iobase + com_data);
3736         siocnclose(&sp, iobase);
3737         splx(s);
3738         return (c);
3739 }
3740
3741 static void
3742 siocnputc(struct consdev *cd, int c)
3743 {
3744         int     need_unlock;
3745         int     s;
3746         struct siocnstate       sp;
3747         Port_t  iobase;
3748         speed_t speed;
3749
3750         if (cd != NULL && cd->cn_unit == siocnunit) {
3751                 iobase = siocniobase;
3752                 speed = comdefaultrate;
3753         } else {
3754 #ifdef GDB
3755                 iobase = siogdbiobase;
3756                 speed = gdbdefaultrate;
3757 #else
3758                 return;
3759 #endif
3760         }
3761         s = spltty();
3762         need_unlock = 0;
3763         if (!kdb_active && sio_inited == 2 && !mtx_owned(&sio_lock)) {
3764                 mtx_lock_spin(&sio_lock);
3765                 need_unlock = 1;
3766         }
3767         siocnopen(&sp, iobase, speed);
3768         siocntxwait(iobase);
3769         outb(iobase + com_data, c);
3770         siocnclose(&sp, iobase);
3771         if (need_unlock)
3772                 mtx_unlock_spin(&sio_lock);
3773         splx(s);
3774 }
3775
3776 /*
3777  * Remote gdb(1) support.
3778  */
3779
3780 #if defined(GDB)
3781
3782 #include <gdb/gdb.h>
3783
3784 static gdb_probe_f siogdbprobe;
3785 static gdb_init_f siogdbinit;
3786 static gdb_term_f siogdbterm;
3787 static gdb_getc_f siogdbgetc;
3788 static gdb_checkc_f siogdbcheckc;
3789 static gdb_putc_f siogdbputc;
3790
3791 GDB_DBGPORT(sio, siogdbprobe, siogdbinit, siogdbterm, siogdbcheckc,
3792     siogdbgetc, siogdbputc);
3793
3794 static int
3795 siogdbprobe(void)
3796 {
3797         return ((siogdbiobase != 0) ? 0 : -1);
3798 }
3799
3800 static void
3801 siogdbinit(void)
3802 {
3803 }
3804
3805 static void
3806 siogdbterm(void)
3807 {
3808 }
3809
3810 static void
3811 siogdbputc(int c)
3812 {
3813         siocnputc(NULL, c);
3814 }
3815
3816 static int
3817 siogdbcheckc(void)
3818 {
3819         return (siocncheckc(NULL));
3820 }
3821
3822 static int
3823 siogdbgetc(void)
3824 {
3825         return (siocngetc(NULL));
3826 }
3827
3828 #endif
3829
3830 #ifdef PC98
3831 /*
3832  *  pc98 local function
3833  */
3834 static void
3835 com_tiocm_bis(struct com_s *com, int msr)
3836 {
3837         int     s;
3838         int     tmp = 0;
3839
3840         s=spltty();
3841         com->pc98_prev_modem_status |= ( msr & (TIOCM_LE|TIOCM_DTR|TIOCM_RTS) );
3842         tmp |= CMD8251_TxEN|CMD8251_RxEN;
3843         if ( msr & TIOCM_DTR ) tmp |= CMD8251_DTR;
3844         if ( msr & TIOCM_RTS ) tmp |= CMD8251_RTS;
3845
3846         pc98_i8251_or_cmd( com, tmp );
3847         splx(s);
3848 }
3849
3850 static void
3851 com_tiocm_bic(struct com_s *com, int msr)
3852 {
3853         int     s;
3854         int     tmp = msr;
3855
3856         s=spltty();
3857         com->pc98_prev_modem_status &= ~( msr & (TIOCM_LE|TIOCM_DTR|TIOCM_RTS) );
3858         if ( msr & TIOCM_DTR ) tmp |= CMD8251_DTR;
3859         if ( msr & TIOCM_RTS ) tmp |= CMD8251_RTS;
3860
3861         pc98_i8251_clear_cmd( com, tmp );
3862         splx(s);
3863 }
3864
3865 static int
3866 com_tiocm_get(struct com_s *com)
3867 {
3868         return( com->pc98_prev_modem_status );
3869 }
3870
3871 static int
3872 com_tiocm_get_delta(struct com_s *com)
3873 {
3874         int     tmp;
3875
3876         tmp = com->pc98_modem_delta;
3877         com->pc98_modem_delta = 0;
3878         return( tmp );
3879 }
3880
3881 /* convert to TIOCM_?? ( ioctl.h ) */
3882 static int
3883 pc98_get_modem_status(struct com_s *com)
3884 {
3885         register int    msr;
3886
3887         msr = com->pc98_prev_modem_status
3888                         & ~(TIOCM_CAR|TIOCM_RI|TIOCM_DSR|TIOCM_CTS);
3889         if (com->pc98_8251fifo_enable) {
3890                 int     stat2;
3891
3892                 stat2 = inb(I8251F_msr);
3893                 if ( stat2 & CICSCDF_CD ) msr |= TIOCM_CAR;
3894                 if ( stat2 & CICSCDF_CI ) msr |= TIOCM_RI;
3895                 if ( stat2 & CICSCDF_DR ) msr |= TIOCM_DSR;
3896                 if ( stat2 & CICSCDF_CS ) msr |= TIOCM_CTS;
3897 #if COM_CARRIER_DETECT_EMULATE
3898                 if ( msr & (TIOCM_DSR|TIOCM_CTS) ) {
3899                         msr |= TIOCM_CAR;
3900                 }
3901 #endif
3902         } else {
3903                 int     stat, stat2;
3904                 
3905                 stat  = inb(com->sts_port);
3906                 stat2 = inb(com->in_modem_port);
3907                 if ( !(stat2 & CICSCD_CD) ) msr |= TIOCM_CAR;
3908                 if ( !(stat2 & CICSCD_CI) ) msr |= TIOCM_RI;
3909                 if (   stat & STS8251_DSR ) msr |= TIOCM_DSR;
3910                 if ( !(stat2 & CICSCD_CS) ) msr |= TIOCM_CTS;
3911 #if COM_CARRIER_DETECT_EMULATE
3912                 if ( msr & (TIOCM_DSR|TIOCM_CTS) ) {
3913                         msr |= TIOCM_CAR;
3914                 }
3915 #endif
3916         }
3917         return(msr);
3918 }
3919
3920 static void
3921 pc98_check_msr(void* chan)
3922 {
3923         int     msr, delta;
3924         int     s;
3925         register struct tty *tp;
3926         struct  com_s *com;
3927         struct cdev *dev;
3928
3929         dev=(struct cdev *)chan;
3930         com = dev->si_drv1;
3931         tp = dev->si_tty;
3932
3933         s = spltty();
3934         msr = pc98_get_modem_status(com);
3935         /* make change flag */
3936         delta = msr ^ com->pc98_prev_modem_status;
3937         if ( delta & TIOCM_CAR ) {
3938             if ( com->modem_car_chg_timer ) {
3939                 if ( -- com->modem_car_chg_timer )
3940                     msr ^= TIOCM_CAR;
3941             } else {
3942                 if ((com->modem_car_chg_timer = (msr & TIOCM_CAR) ?
3943                      DCD_ON_RECOGNITION : DCD_OFF_TOLERANCE) != 0)
3944                     msr ^= TIOCM_CAR;
3945             }
3946         } else
3947             com->modem_car_chg_timer = 0;
3948         delta = ( msr ^ com->pc98_prev_modem_status ) &
3949                         (TIOCM_CAR|TIOCM_RI|TIOCM_DSR|TIOCM_CTS);
3950         com->pc98_prev_modem_status = msr;
3951         delta = ( com->pc98_modem_delta |= delta );
3952         splx(s);
3953         if ( com->modem_checking || (tp->t_state & (TS_ISOPEN)) ) {
3954                 if ( delta ) {
3955                         commint(dev);
3956                 }
3957                 timeout(pc98_check_msr, (caddr_t)dev,
3958                                         PC98_CHECK_MODEM_INTERVAL);
3959         } else {
3960                 com->modem_checking = 0;
3961         }
3962 }
3963
3964 static void
3965 pc98_msrint_start(struct cdev *dev)
3966 {
3967         struct  com_s *com;
3968         int     s = spltty();
3969
3970         com = dev->si_drv1;
3971         /* modem control line check routine envoke interval is 1/10 sec */
3972         if ( com->modem_checking == 0 ) {
3973                 com->pc98_prev_modem_status = pc98_get_modem_status(com);
3974                 com->pc98_modem_delta = 0;
3975                 timeout(pc98_check_msr, (caddr_t)dev,
3976                                         PC98_CHECK_MODEM_INTERVAL);
3977                 com->modem_checking = 1;
3978         }
3979         splx(s);
3980 }
3981
3982 static void
3983 pc98_disable_i8251_interrupt(struct com_s *com, int mod)
3984 {
3985         /* disable interrupt */
3986         register int    tmp;
3987
3988         mod |= ~(IEN_Tx|IEN_TxEMP|IEN_Rx);
3989         COM_INT_DISABLE
3990         tmp = inb( com->intr_ctrl_port ) & ~(IEN_Tx|IEN_TxEMP|IEN_Rx);
3991         outb( com->intr_ctrl_port, (com->intr_enable&=~mod) | tmp );
3992         COM_INT_ENABLE
3993 }
3994
3995 static void
3996 pc98_enable_i8251_interrupt(struct com_s *com, int mod)
3997 {
3998         register int    tmp;
3999
4000         COM_INT_DISABLE
4001         tmp = inb( com->intr_ctrl_port ) & ~(IEN_Tx|IEN_TxEMP|IEN_Rx);
4002         outb( com->intr_ctrl_port, (com->intr_enable|=mod) | tmp );
4003         COM_INT_ENABLE
4004 }
4005
4006 static int
4007 pc98_check_i8251_interrupt(struct com_s *com)
4008 {
4009         return ( com->intr_enable & 0x07 );
4010 }
4011
4012 static void
4013 pc98_i8251_clear_cmd(struct com_s *com, int x)
4014 {
4015         int     tmp;
4016
4017         COM_INT_DISABLE
4018         tmp = com->pc98_prev_siocmd & ~(x);
4019         if (com->pc98_8251fifo_enable)
4020             outb(I8251F_fcr, 0);
4021         outb(com->cmd_port, tmp);
4022         com->pc98_prev_siocmd = tmp & ~(CMD8251_ER|CMD8251_RESET|CMD8251_EH);
4023         if (com->pc98_8251fifo_enable)
4024             outb(I8251F_fcr, CTRL8251F_ENABLE);
4025         COM_INT_ENABLE
4026 }
4027
4028 static void
4029 pc98_i8251_or_cmd(struct com_s *com, int x)
4030 {
4031         int     tmp;
4032
4033         COM_INT_DISABLE
4034         if (com->pc98_8251fifo_enable)
4035             outb(I8251F_fcr, 0);
4036         tmp = com->pc98_prev_siocmd | (x);
4037         outb(com->cmd_port, tmp);
4038         com->pc98_prev_siocmd = tmp & ~(CMD8251_ER|CMD8251_RESET|CMD8251_EH);
4039         if (com->pc98_8251fifo_enable)
4040             outb(I8251F_fcr, CTRL8251F_ENABLE);
4041         COM_INT_ENABLE
4042 }
4043
4044 static void
4045 pc98_i8251_set_cmd(struct com_s *com, int x)
4046 {
4047         int     tmp;
4048
4049         COM_INT_DISABLE
4050         if (com->pc98_8251fifo_enable)
4051             outb(I8251F_fcr, 0);
4052         tmp = (x);
4053         outb(com->cmd_port, tmp);
4054         com->pc98_prev_siocmd = tmp & ~(CMD8251_ER|CMD8251_RESET|CMD8251_EH);
4055         if (com->pc98_8251fifo_enable)
4056             outb(I8251F_fcr, CTRL8251F_ENABLE);
4057         COM_INT_ENABLE
4058 }
4059
4060 static void
4061 pc98_i8251_clear_or_cmd(struct com_s *com, int clr, int x)
4062 {
4063         int     tmp;
4064         COM_INT_DISABLE
4065         if (com->pc98_8251fifo_enable)
4066             outb(I8251F_fcr, 0);
4067         tmp = com->pc98_prev_siocmd & ~(clr);
4068         tmp |= (x);
4069         outb(com->cmd_port, tmp);
4070         com->pc98_prev_siocmd = tmp & ~(CMD8251_ER|CMD8251_RESET|CMD8251_EH);
4071         if (com->pc98_8251fifo_enable)
4072             outb(I8251F_fcr, CTRL8251F_ENABLE);
4073         COM_INT_ENABLE
4074 }
4075
4076 static int
4077 pc98_i8251_get_cmd(struct com_s *com)
4078 {
4079         return com->pc98_prev_siocmd;
4080 }
4081
4082 static int
4083 pc98_i8251_get_mod(struct com_s *com)
4084 {
4085         return com->pc98_prev_siomod;
4086 }
4087
4088 static void
4089 pc98_i8251_reset(struct com_s *com, int mode, int command)
4090 {
4091         if (com->pc98_8251fifo_enable)
4092             outb(I8251F_fcr, 0);
4093         outb(com->cmd_port, 0); /* dummy */
4094         DELAY(2);
4095         outb(com->cmd_port, 0); /* dummy */
4096         DELAY(2);
4097         outb(com->cmd_port, 0); /* dummy */
4098         DELAY(2);
4099         outb(com->cmd_port, CMD8251_RESET);     /* internal reset */
4100         DELAY(2);
4101         outb(com->cmd_port, mode );     /* mode register */
4102         com->pc98_prev_siomod = mode;
4103         DELAY(2);
4104         pc98_i8251_set_cmd( com, (command|CMD8251_ER) );
4105         DELAY(10);
4106         if (com->pc98_8251fifo_enable)
4107             outb(I8251F_fcr, CTRL8251F_ENABLE |
4108                  CTRL8251F_XMT_RST | CTRL8251F_RCV_RST);
4109 }
4110
4111 static void
4112 pc98_check_sysclock(void)
4113 {
4114         /* get system clock from port */
4115         if ( pc98_machine_type & M_8M ) {
4116         /* 8 MHz system & H98 */
4117                 sysclock = 8;
4118         } else {
4119         /* 5 MHz system */
4120                 sysclock = 5;
4121         }
4122 }
4123
4124 static void
4125 com_cflag_and_speed_set( struct com_s *com, int cflag, int speed)
4126 {
4127         int     cfcr=0;
4128         int     previnterrupt;
4129         int     tmp;
4130         u_int   count;
4131
4132         if (pc98_ttspeedtab(com, speed, &count) != 0)
4133                 return;
4134
4135         previnterrupt = pc98_check_i8251_interrupt(com);
4136         pc98_disable_i8251_interrupt( com, IEN_Tx|IEN_TxEMP|IEN_Rx );
4137
4138         switch ( cflag&CSIZE ) {
4139           case CS5:
4140                 cfcr = MOD8251_5BITS; break;
4141           case CS6:
4142                 cfcr = MOD8251_6BITS; break;
4143           case CS7:
4144                 cfcr = MOD8251_7BITS; break;
4145           case CS8:
4146                 cfcr = MOD8251_8BITS; break;
4147         }
4148         if ( cflag&PARENB ) {
4149             if ( cflag&PARODD )
4150                 cfcr |= MOD8251_PODD;
4151             else
4152                 cfcr |= MOD8251_PEVEN;
4153         } else
4154                 cfcr |= MOD8251_PDISAB;
4155
4156         if ( cflag&CSTOPB )
4157                 cfcr |= MOD8251_STOP2;
4158         else
4159                 cfcr |= MOD8251_STOP1;
4160
4161         if ( count & 0x10000 )
4162                 cfcr |= MOD8251_CLKX1;
4163         else
4164                 cfcr |= MOD8251_CLKX16;
4165
4166         while (!((tmp = inb(com->sts_port)) & STS8251_TxEMP))
4167                 ;
4168
4169         /* set baud rate from ospeed */
4170         pc98_set_baud_rate( com, count );
4171
4172         if ( cfcr != pc98_i8251_get_mod(com) )
4173                 pc98_i8251_reset(com, cfcr, pc98_i8251_get_cmd(com) );
4174
4175         pc98_enable_i8251_interrupt( com, previnterrupt );
4176 }
4177
4178 static int
4179 pc98_ttspeedtab(struct com_s *com, int speed, u_int *divisor)
4180 {
4181         int     if_type, effect_sp, count = -1, mod;
4182
4183         if_type = com->pc98_if_type & 0x0f;
4184
4185         switch (com->pc98_if_type) {
4186         case COM_IF_INTERNAL:
4187             if (PC98SIO_baud_rate_port(if_type) != -1) {
4188                 count = ttspeedtab(speed, if_8251_type[if_type].speedtab);
4189                 if (count > 0) {
4190                     count |= COM1_EXT_CLOCK;
4191                     break;
4192                 }
4193             }
4194
4195             /* for *1CLK asynchronous! mode, TEFUTEFU */
4196             mod = (sysclock == 5) ? 2457600 : 1996800;
4197             effect_sp = ttspeedtab( speed, pc98speedtab );
4198             if ( effect_sp < 0 )        /* XXX */
4199                 effect_sp = ttspeedtab( (speed - 1), pc98speedtab );
4200             if ( effect_sp <= 0 )
4201                 return effect_sp;
4202             if ( effect_sp == speed )
4203                 mod /= 16;
4204             if ( mod % effect_sp )
4205                 return(-1);
4206             count = mod / effect_sp;
4207             if ( count > 65535 )
4208                 return(-1);
4209             if ( effect_sp != speed )
4210                 count |= 0x10000;
4211             break;
4212         case COM_IF_PC9861K_1:
4213         case COM_IF_PC9861K_2:
4214             count = 1;
4215             break;
4216         case COM_IF_IND_SS_1:
4217         case COM_IF_IND_SS_2:
4218         case COM_IF_PIO9032B_1:
4219         case COM_IF_PIO9032B_2:
4220             count = ttspeedtab( speed, if_8251_type[if_type].speedtab );
4221             break;
4222         case COM_IF_B98_01_1:
4223         case COM_IF_B98_01_2:
4224             count = ttspeedtab( speed, if_8251_type[if_type].speedtab );
4225 #ifdef B98_01_OLD
4226             if (count == 0 || count == 1) {
4227                 count += 4;
4228                 count |= 0x20000;  /* x1 mode for 76800 and 153600 */
4229             }
4230 #endif
4231             break;
4232         }
4233
4234         if (count < 0)
4235                 return count;
4236
4237         *divisor = (u_int) count;
4238         return 0;
4239 }
4240
4241 static void
4242 pc98_set_baud_rate( struct com_s *com, u_int count )
4243 {
4244         int     if_type, io, s;
4245
4246         if_type = com->pc98_if_type & 0x0f;
4247         io = rman_get_start(com->ioportres) & 0xff00;
4248
4249         switch (com->pc98_if_type) {
4250         case COM_IF_INTERNAL:
4251             if (PC98SIO_baud_rate_port(if_type) != -1) {
4252                 if (count & COM1_EXT_CLOCK) {
4253                     outb((Port_t)PC98SIO_baud_rate_port(if_type), count & 0xff);
4254                     break;
4255                 } else {
4256                     outb((Port_t)PC98SIO_baud_rate_port(if_type), 0x09);
4257                 }
4258             }
4259
4260             if (count == 0)
4261                 return;
4262
4263             /* set i8253 */
4264             s = splclock();
4265             if (count != 3)
4266                 outb( 0x77, 0xb6 );
4267             else
4268                 outb( 0x77, 0xb4 );
4269             outb( 0x5f, 0);
4270             outb( 0x75, count & 0xff );
4271             outb( 0x5f, 0);
4272             outb( 0x75, (count >> 8) & 0xff );
4273             splx(s);
4274             break;
4275         case COM_IF_IND_SS_1:
4276         case COM_IF_IND_SS_2:
4277             outb(io | PC98SIO_intr_ctrl_port(if_type), 0);
4278             outb(io | PC98SIO_baud_rate_port(if_type), 0);
4279             outb(io | PC98SIO_baud_rate_port(if_type), 0xc0);
4280             outb(io | PC98SIO_baud_rate_port(if_type), (count >> 8) | 0x80);
4281             outb(io | PC98SIO_baud_rate_port(if_type), count & 0xff);
4282             break;
4283         case COM_IF_PIO9032B_1:
4284         case COM_IF_PIO9032B_2:
4285             outb(io | PC98SIO_baud_rate_port(if_type), count);
4286             break;
4287         case COM_IF_B98_01_1:
4288         case COM_IF_B98_01_2:
4289             outb(io | PC98SIO_baud_rate_port(if_type), count & 0x0f);
4290 #ifdef B98_01_OLD
4291             /*
4292              * Some old B98_01 board should be controlled
4293              * in different way, but this hasn't been tested yet.
4294              */
4295             outb(io | PC98SIO_func_port(if_type),
4296                  (count & 0x20000) ? 0xf0 : 0xf2);
4297 #endif
4298             break;
4299         }
4300 }
4301 static int
4302 pc98_check_if_type(device_t dev, struct siodev *iod)
4303 {
4304         int     irr, io, if_type, tmp;
4305         static  short   irq_tab[2][8] = {
4306                 {  3,  5,  6,  9, 10, 12, 13, -1},
4307                 {  3, 10, 12, 13,  5,  6,  9, -1}
4308         };
4309
4310         if_type = iod->if_type & 0x0f;
4311         iod->irq = 0;
4312         io = isa_get_port(dev) & 0xff00;
4313
4314         if (IS_8251(iod->if_type)) {
4315             if (PC98SIO_func_port(if_type) != -1) {
4316                 outb(io | PC98SIO_func_port(if_type), 0xf2);
4317                 tmp = ttspeedtab(9600, if_8251_type[if_type].speedtab);
4318                 if (tmp != -1 && PC98SIO_baud_rate_port(if_type) != -1)
4319                     outb(io | PC98SIO_baud_rate_port(if_type), tmp);
4320             }
4321
4322             iod->cmd  = io | PC98SIO_cmd_port(if_type);
4323             iod->sts  = io | PC98SIO_sts_port(if_type);
4324             iod->mod  = io | PC98SIO_in_modem_port(if_type);
4325             iod->ctrl = io | PC98SIO_intr_ctrl_port(if_type);
4326
4327             if (iod->if_type == COM_IF_INTERNAL) {
4328                 iod->irq = 4;
4329
4330                 if (pc98_check_8251vfast()) {
4331                         PC98SIO_baud_rate_port(if_type) = I8251F_div;
4332                         if_8251_type[if_type].speedtab = pc98fast_speedtab;
4333                 }
4334             } else {
4335                 tmp = inb( iod->mod ) & if_8251_type[if_type].irr_mask;
4336                 if ((isa_get_port(dev) & 0xff) == IO_COM2)
4337                     iod->irq = irq_tab[0][tmp];
4338                 else
4339                     iod->irq = irq_tab[1][tmp];
4340             }
4341         } else {
4342             irr = if_16550a_type[if_type].irr_read;
4343 #ifdef COM_MULTIPORT
4344             if (!COM_ISMULTIPORT(device_get_flags(dev)) ||
4345                     device_get_unit(dev) == COM_MPMASTER(device_get_flags(dev)))
4346 #endif
4347             if (irr != -1) {
4348                 tmp = inb(io | irr);
4349                 if (isa_get_port(dev) & 0x01)   /* XXX depend on RSB-384 */
4350                     iod->irq = irq_tab[1][tmp >> 3];
4351                 else
4352                     iod->irq = irq_tab[0][tmp & 0x07];
4353             }
4354         }
4355         if ( iod->irq == -1 ) return -1;
4356
4357         return 0;
4358 }
4359 static void
4360 pc98_set_ioport(struct com_s *com)
4361 {
4362         int     if_type = com->pc98_if_type & 0x0f;
4363         Port_t  io = rman_get_start(com->ioportres) & 0xff00;
4364
4365         pc98_check_sysclock();
4366         com->data_port          = io | PC98SIO_data_port(if_type);
4367         com->cmd_port           = io | PC98SIO_cmd_port(if_type);
4368         com->sts_port           = io | PC98SIO_sts_port(if_type);
4369         com->in_modem_port      = io | PC98SIO_in_modem_port(if_type);
4370         com->intr_ctrl_port     = io | PC98SIO_intr_ctrl_port(if_type);
4371 }
4372 static int
4373 pc98_check_8251vfast(void)
4374 {
4375     int i;
4376
4377     outb(I8251F_div, 0x8c);
4378     DELAY(10);
4379     for (i = 0; i < 100; i++) {
4380         if ((inb(I8251F_div) & 0x80) != 0) {
4381             i = 0;
4382             break;
4383         }
4384         DELAY(1);
4385     }
4386     outb(I8251F_div, 0);
4387     DELAY(10);
4388     for (; i < 100; i++) {
4389         if ((inb(I8251F_div) & 0x80) == 0)
4390             return 1;
4391         DELAY(1);
4392     }
4393
4394     return 0;
4395 }
4396 static int
4397 pc98_check_8251fifo(void)
4398 {
4399     u_char      tmp1, tmp2;
4400
4401     tmp1 = inb(I8251F_iir);
4402     DELAY(10);
4403     tmp2 = inb(I8251F_iir);
4404     if (((tmp1 ^ tmp2) & 0x40) != 0 && ((tmp1 | tmp2) & 0x20) == 0)
4405         return 1;
4406
4407     return 0;
4408 }
4409 #endif /* PC98 defined */