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