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