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