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