cy(4): Remove ISA support.
[dragonfly.git] / sys / dev / serial / cy / cy.c
1 /*-
2  * (MPSAFE)
3  *
4  * cyclades cyclom-y serial driver
5  *      Andrew Herbert <andrew@werple.apana.org.au>, 17 August 1993
6  *
7  * Copyright (c) 1993 Andrew Herbert.
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. The name Andrew Herbert may not be used to endorse or promote products
19  *    derived from this software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY ``AS IS'' AND ANY EXPRESS OR IMPLIED
22  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
23  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN
24  * NO EVENT SHALL I BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
25  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
26  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
27  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
28  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
29  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
30  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  *
32  * $FreeBSD: src/sys/i386/isa/cy.c,v 1.97.2.2 2001/08/22 13:04:58 bde Exp $
33  */
34
35 #include "opt_compat.h"
36 #include "use_cy.h"
37
38 /*
39  * TODO:
40  * Atomic COR change.
41  * Consoles.
42  */
43
44 /*
45  * Temporary compile-time configuration options.
46  */
47 #define RxFifoThreshold (CD1400_RX_FIFO_SIZE / 2)
48                         /* Number of chars in the receiver FIFO before an
49                          * an interrupt is generated.  Should depend on
50                          * line speed.  Needs to be about 6 on a 486DX33
51                          * for 4 active ports at 115200 bps.  Why doesn't
52                          * 10 work?
53                          */
54 #define PollMode        /* Use polling-based irq service routine, not the
55                          * hardware svcack lines.  Must be defined for
56                          * Cyclom-16Y boards.  Less efficient for Cyclom-8Ys,
57                          * and stops 4 * 115200 bps from working.
58                          */
59 #undef  Smarts          /* Enable slightly more CD1400 intelligence.  Mainly
60                          * the output CR/LF processing, plus we can avoid a
61                          * few checks usually done in ttyinput().
62                          *
63                          * XXX not fully implemented, and not particularly
64                          * worthwhile.
65                          */
66 #undef  CyDebug         /* Include debugging code (not very expensive). */
67
68 /* These will go away. */
69 #undef  SOFT_CTS_OFLOW
70 #define SOFT_HOTCHAR
71
72 #include <sys/param.h>
73 #include <sys/systm.h>
74 #include <sys/tty.h>
75 #include <sys/proc.h>
76 #include <sys/priv.h>
77 #include <sys/conf.h>
78 #include <sys/dkstat.h>
79 #include <sys/fcntl.h>
80 #include <sys/interrupt.h>
81 #include <sys/kernel.h>
82 #include <sys/malloc.h>
83 #include <sys/syslog.h>
84 #include <sys/thread2.h>
85 #include <machine/clock.h>
86 #include <machine/psl.h>
87
88 #include "cyreg.h"
89 #include <machine_base/isa/ic/cd1400.h>
90
91 #define disable_intr()  com_lock()
92 #define enable_intr()   com_unlock()
93
94 /*
95  * Dictionary so that I can name everything *sio* or *com* to compare with
96  * sio.c.  There is also lots of ugly formatting and unnecessary ifdefs to
97  * simplify the comparision.  These will go away.
98  */
99 #define LSR_BI          CD1400_RDSR_BREAK
100 #define LSR_FE          CD1400_RDSR_FE
101 #define LSR_OE          CD1400_RDSR_OE
102 #define LSR_PE          CD1400_RDSR_PE
103 #define MCR_DTR         CD1400_MSVR2_DTR
104 #define MCR_RTS         CD1400_MSVR1_RTS
105 #define MSR_CTS         CD1400_MSVR2_CTS
106 #define MSR_DCD         CD1400_MSVR2_CD
107 #define MSR_DSR         CD1400_MSVR2_DSR
108 #define MSR_RI          CD1400_MSVR2_RI
109 #define NSIO            (NCY * CY_MAX_PORTS)
110 #define comconsole      cyconsole
111 #define comdefaultrate  cydefaultrate
112 #define com_events      cy_events
113 #define comhardclose    cyhardclose
114 #define commctl         cymctl
115 #define comparam        cyparam
116 #define comspeed        cyspeed
117 #define comstart        cystart
118 #define comwakeup       cywakeup
119 #define nsio_tty        ncy_tty
120 #define p_com_addr      p_cy_addr
121 #define sioattach       cyattach
122 #define sioclose        cyclose
123 #define siodriver       cydriver
124 #define siodtrwakeup    cydtrwakeup
125 #define sioinput        cyinput
126 #define siointr         cyintr
127 #define siointr1        cyintr1
128 #define sioioctl        cyioctl
129 #define sioopen         cyopen
130 #define siopoll         cypoll
131 #define sioprobe        cyprobe
132 #define siosettimeout   cysettimeout
133 #define siosetwater     cysetwater
134 #define comstop         cystop
135 #define siowrite        cywrite
136 #define sio_registered  cy_registered
137 #define sio_timeout     cy_timeout
138 #define sio_timeout_handle cy_timeout_handle
139 #define sio_timeouts_until_log  cy_timeouts_until_log
140 #define sio_tty         cy_tty
141
142 #define CY_MAX_PORTS            (CD1400_NO_OF_CHANNELS * CY_MAX_CD1400s)
143
144 /* We encode the cyclom unit number (cyu) in spare bits in the IVR's. */
145 #define CD1400_xIVR_CHAN_SHIFT  3
146 #define CD1400_xIVR_CHAN        0x1F
147
148 /*
149  * ETC states.  com->etc may also contain a hardware ETC command value,
150  * meaning that execution of that command is pending.
151  */
152 #define ETC_NONE                0       /* we depend on bzero() setting this */
153 #define ETC_BREAK_STARTING      1
154 #define ETC_BREAK_STARTED       2
155 #define ETC_BREAK_ENDING        3
156 #define ETC_BREAK_ENDED         4
157
158 #define LOTS_OF_EVENTS  64      /* helps separate urgent events from input */
159
160 #define CALLOUT_MASK            0x80
161 #define CONTROL_MASK            0x60
162 #define CONTROL_INIT_STATE      0x20
163 #define CONTROL_LOCK_STATE      0x40
164 #define DEV_TO_UNIT(dev)        (MINOR_TO_UNIT(minor(dev)))
165 #define MINOR_MAGIC_MASK        (CALLOUT_MASK | CONTROL_MASK)
166 /*
167  * Not all of the magic is parametrized in the following macros.  16 and
168  * 0xff are related to the bitfields in a udev_t.  CY_MAX_PORTS must be
169  * ((0xff & ~MINOR_MAGIC_MASK) + 1) for things to work.
170  */
171 #define MINOR_TO_UNIT(mynor)    (((mynor) >> 16) * CY_MAX_PORTS \
172                                  | (((mynor) & 0xff) & ~MINOR_MAGIC_MASK))
173 #define UNIT_TO_MINOR(unit)     (((unit) / CY_MAX_PORTS) << 16 \
174                                  | (((unit) & 0xff) & ~MINOR_MAGIC_MASK))
175
176 /*
177  * com state bits.
178  * (CS_BUSY | CS_TTGO) and (CS_BUSY | CS_TTGO | CS_ODEVREADY) must be higher
179  * than the other bits so that they can be tested as a group without masking
180  * off the low bits.
181  *
182  * The following com and tty flags correspond closely:
183  *      CS_BUSY         = TS_BUSY (maintained by comstart(), siopoll() and
184  *                                 comstop())
185  *      CS_TTGO         = ~TS_TTSTOP (maintained by comparam() and comstart())
186  *      CS_CTS_OFLOW    = CCTS_OFLOW (maintained by comparam())
187  *      CS_RTS_IFLOW    = CRTS_IFLOW (maintained by comparam())
188  * TS_FLUSH is not used.
189  * XXX I think TIOCSETA doesn't clear TS_TTSTOP when it clears IXON.
190  * XXX CS_*FLOW should be CF_*FLOW in com->flags (control flags not state).
191  */
192 #define CS_BUSY         0x80    /* output in progress */
193 #define CS_TTGO         0x40    /* output not stopped by XOFF */
194 #define CS_ODEVREADY    0x20    /* external device h/w ready (CTS) */
195 #define CS_CHECKMSR     1       /* check of MSR scheduled */
196 #define CS_CTS_OFLOW    2       /* use CTS output flow control */
197 #define CS_DTR_OFF      0x10    /* DTR held off */
198 #define CS_ODONE        4       /* output completed */
199 #define CS_RTS_IFLOW    8       /* use RTS input flow control */
200 #define CSE_ODONE       1       /* output transmitted */
201
202 static  char const * const      error_desc[] = {
203 #define CE_OVERRUN                      0
204         "silo overflow",
205 #define CE_INTERRUPT_BUF_OVERFLOW       1
206         "interrupt-level buffer overflow",
207 #define CE_TTY_BUF_OVERFLOW             2
208         "tty-level buffer overflow",
209 };
210
211 #define CE_NTYPES                       3
212 #define CE_RECORD(com, errnum)          (++(com)->delta_error_counts[errnum])
213
214 /* types.  XXX - should be elsewhere */
215 typedef u_char  bool_t;         /* boolean */
216 typedef u_char volatile *cy_addr;
217
218 /* queue of linear buffers */
219 struct lbq {
220         u_char  *l_head;        /* next char to process */
221         u_char  *l_tail;        /* one past the last char to process */
222         struct lbq *l_next;     /* next in queue */
223         bool_t  l_queued;       /* nonzero if queued */
224 };
225
226 /* com device structure */
227 struct com_s {
228         u_char  state;          /* miscellaneous flag bits */
229         bool_t  active_out;     /* nonzero if the callout device is open */
230 #if 0
231         u_char  cfcr_image;     /* copy of value written to CFCR */
232 #endif
233         u_char  etc;            /* pending Embedded Transmit Command */
234         u_char  extra_state;    /* more flag bits, separate for order trick */
235 #if 0
236         u_char  fifo_image;     /* copy of value written to FIFO */
237 #endif
238         u_char  gfrcr_image;    /* copy of value read from GFRCR */
239 #if 0
240         bool_t  hasfifo;        /* nonzero for 16550 UARTs */
241         bool_t  loses_outints;  /* nonzero if device loses output interrupts */
242 #endif
243         u_char  mcr_dtr;        /* MCR bit that is wired to DTR */
244         u_char  mcr_image;      /* copy of value written to MCR */
245         u_char  mcr_rts;        /* MCR bit that is wired to RTS */
246 #if 0
247 #ifdef COM_MULTIPORT
248         bool_t  multiport;      /* is this unit part of a multiport device? */
249 #endif /* COM_MULTIPORT */
250         bool_t  no_irq;         /* nonzero if irq is not attached */
251         bool_t  poll;           /* nonzero if polling is required */
252         bool_t  poll_output;    /* nonzero if polling for output is required */
253 #endif
254         int     unit;           /* unit number */
255         int     dtr_wait;       /* time to hold DTR down on close (* 1/hz) */
256         struct callout dtr_ch;
257 #if 0
258         u_int   tx_fifo_size;
259 #endif
260         u_int   wopeners;       /* # processes waiting for DCD in open() */
261
262         /*
263          * The high level of the driver never reads status registers directly
264          * because there would be too many side effects to handle conveniently.
265          * Instead, it reads copies of the registers stored here by the
266          * interrupt handler.
267          */
268         u_char  last_modem_status;      /* last MSR read by intr handler */
269         u_char  prev_modem_status;      /* last MSR handled by high level */
270
271         u_char  hotchar;        /* ldisc-specific char to be handled ASAP */
272         u_char  *ibuf;          /* start of input buffer */
273         u_char  *ibufend;       /* end of input buffer */
274         u_char  *ibufold;       /* old input buffer, to be freed */
275         u_char  *ihighwater;    /* threshold in input buffer */
276         u_char  *iptr;          /* next free spot in input buffer */
277         int     ibufsize;       /* size of ibuf (not include error bytes) */
278         int     ierroff;        /* offset of error bytes in ibuf */
279
280         struct lbq      obufq;  /* head of queue of output buffers */
281         struct lbq      obufs[2];       /* output buffers */
282
283         int     cy_align;       /* index for register alignment */
284         cy_addr cy_iobase;      /* base address of this port's cyclom */
285         cy_addr iobase;         /* base address of this port's cd1400 */
286         int     mcr_rts_reg;    /* cd1400 reg number of reg holding mcr_rts */
287
288         struct tty      *tp;    /* cross reference */
289
290         /* Initial state. */
291         struct termios  it_in;  /* should be in struct tty */
292         struct termios  it_out;
293
294         /* Lock state. */
295         struct termios  lt_in;  /* should be in struct tty */
296         struct termios  lt_out;
297
298         bool_t  do_timestamp;
299         bool_t  do_dcd_timestamp;
300         struct timeval  timestamp;
301         struct timeval  dcd_timestamp;
302
303         u_long  bytes_in;       /* statistics */
304         u_long  bytes_out;
305         u_int   delta_error_counts[CE_NTYPES];
306         u_long  error_counts[CE_NTYPES];
307
308         u_int   recv_exception; /* exception chars received */
309         u_int   mdm;            /* modem signal changes */
310 #ifdef CyDebug
311         u_int   start_count;    /* no. of calls to comstart() */
312         u_int   start_real;     /* no. of calls that did something */
313 #endif
314         u_char  car;            /* CD1400 CAR shadow (if first unit in cd) */
315         u_char  channel_control;/* CD1400 CCR control command shadow */
316         u_char  cor[3];         /* CD1400 COR1-3 shadows */
317         u_char  intr_enable;    /* CD1400 SRER shadow */
318
319         /*
320          * Data area for output buffers.  Someday we should build the output
321          * buffer queue without copying data.
322          */
323         u_char  obuf1[256];
324         u_char  obuf2[256];
325 };
326
327 /* PCI driver entry point. */
328 int     cyattach_common         (cy_addr cy_iobase, int cy_align);
329 void    siointr(void *);
330
331 static  int     cy_units        (cy_addr cy_iobase, int cy_align);
332 static  void    cd1400_channel_cmd (struct com_s *com, int cmd);
333 static  void    cd1400_channel_cmd_wait (struct com_s *com);
334 static  void    cd_etc          (struct com_s *com, int etc);
335 static  int     cd_getreg       (struct com_s *com, int reg);
336 static  void    cd_setreg       (struct com_s *com, int reg, int val);
337 static  timeout_t siodtrwakeup;
338 static  void    comhardclose    (struct com_s *com);
339 static  void    sioinput        (struct com_s *com);
340 #if 0
341 static  void    siointr1        (struct com_s *com);
342 #endif
343 static  int     commctl         (struct com_s *com, int bits, int how);
344 static  int     comparam        (struct tty *tp, struct termios *t);
345 static  inthand2_t siopoll;
346 static  void    siosettimeout   (void);
347 static  int     siosetwater     (struct com_s *com, speed_t speed);
348 static  int     comspeed        (speed_t speed, u_long cy_clock,
349                                      int *prescaler_io);
350 static  void    comstart        (struct tty *tp);
351 static  void    comstop         (struct tty *tp, int rw);
352 static  timeout_t comwakeup;
353 static  void    disc_optim      (struct tty     *tp, struct termios *t,
354                                      struct com_s *com);
355
356 #ifdef CyDebug
357 void    cystatus        (int unit);
358 #endif
359
360 static char driver_name[] = "cy";
361
362 /* table and macro for fast conversion from a unit number to its com struct */
363 static  struct com_s    *p_com_addr[NSIO];
364 #define com_addr(unit)  (p_com_addr[unit])
365
366 static  d_open_t        sioopen;
367 static  d_close_t       sioclose;
368 static  d_write_t       siowrite;
369 static  d_ioctl_t       sioioctl;
370
371 static struct dev_ops sio_ops = {
372         { driver_name, 0, D_TTY },
373         .d_open =       sioopen,
374         .d_close =      sioclose,
375         .d_read =       ttyread,
376         .d_write =      siowrite,
377         .d_ioctl =      sioioctl,
378         .d_kqfilter =   ttykqfilter,
379         .d_revoke =     ttyrevoke
380 };
381
382 static  int     comconsole = -1;
383 static  speed_t comdefaultrate = TTYDEF_SPEED;
384 static  u_int   com_events;     /* input chars + weighted output completions */
385 static  bool_t  sio_registered;
386 static  int     sio_timeout;
387 static  int     sio_timeouts_until_log;
388 static  struct  callout sio_timeout_handle;
389 #if 0 /* XXX */
390 static struct tty       *sio_tty[NSIO];
391 #else
392 static struct tty       sio_tty[NSIO];
393 #endif
394 static  const int       nsio_tty = NSIO;
395
396 #ifdef CyDebug
397 static  u_int   cd_inbs;
398 static  u_int   cy_inbs;
399 static  u_int   cd_outbs;
400 static  u_int   cy_outbs;
401 static  u_int   cy_svrr_probes;
402 static  u_int   cy_timeouts;
403 #endif
404
405 static  int     cy_chip_offset[] = {
406         0x0000, 0x0400, 0x0800, 0x0c00, 0x0200, 0x0600, 0x0a00, 0x0e00,
407 };
408 static  int     cy_nr_cd1400s[NCY];
409 static  int     cy_total_devices;
410 #undef  RxFifoThreshold
411 static  int     volatile RxFifoThreshold = (CD1400_RX_FIFO_SIZE / 2);
412
413 static int
414 cy_units(cy_addr cy_iobase, int cy_align)
415 {
416         int     cyu;
417         u_char  firmware_version = 0;  /* assign to avoid warning */
418         int     i;
419         cy_addr iobase;
420
421         for (cyu = 0; cyu < CY_MAX_CD1400s; ++cyu) {
422                 iobase = cy_iobase + (cy_chip_offset[cyu] << cy_align);
423
424                 /* wait for chip to become ready for new command */
425                 for (i = 0; i < 10; i++) {
426                         DELAY(50);
427                         if (!cd_inb(iobase, CD1400_CCR, cy_align))
428                                 break;
429                 }
430
431                 /* clear the GFRCR register */
432                 cd_outb(iobase, CD1400_GFRCR, cy_align, 0);
433
434                 /* issue a reset command */
435                 cd_outb(iobase, CD1400_CCR, cy_align,
436                         CD1400_CCR_CMDRESET | CD1400_CCR_FULLRESET);
437
438                 /* wait for the CD1400 to initialize itself */
439                 for (i = 0; i < 200; i++) {
440                         DELAY(50);
441
442                         /* retrieve firmware version */
443                         firmware_version = cd_inb(iobase, CD1400_GFRCR,
444                                                   cy_align);
445                         if ((firmware_version & 0xf0) == 0x40)
446                                 break;
447                 }
448
449                 /*
450                  * Anything in the 0x40-0x4F range is fine.
451                  * If one CD1400 is bad then we don't support higher
452                  * numbered good ones on this board.
453                  */
454                 if ((firmware_version & 0xf0) != 0x40)
455                         break;
456         }
457         return (cyu);
458 }
459
460 /*
461  * NOTE: Must be called with tty_token held
462  */
463 int
464 cyattach_common(cy_addr cy_iobase, int cy_align)
465 {
466         int     adapter;
467         int     cyu;
468         u_char  firmware_version;
469         cy_addr iobase;
470         int     minorbase;
471         int     ncyu;
472         int     unit;
473
474         ASSERT_LWKT_TOKEN_HELD(&tty_token);
475
476         adapter = cy_total_devices;
477         if ((u_int)adapter >= NCY) {
478                 kprintf(
479         "cy%d: can't attach adapter: insufficient cy devices configured\n",
480                        adapter);
481                 return (-1);
482         }
483         ncyu = cy_units(cy_iobase, cy_align);
484         if (ncyu == 0)
485                 return (-1);
486         cy_nr_cd1400s[adapter] = ncyu;
487         cy_total_devices++;
488
489         unit = adapter * CY_MAX_PORTS;
490         for (cyu = 0; cyu < ncyu; ++cyu) {
491                 int     cdu;
492
493                 iobase = (cy_addr) (cy_iobase
494                                     + (cy_chip_offset[cyu] << cy_align));
495                 firmware_version = cd_inb(iobase, CD1400_GFRCR, cy_align);
496
497                 /* Set up a receive timeout period of than 1+ ms. */
498                 cd_outb(iobase, CD1400_PPR, cy_align,
499                         howmany(CY_CLOCK(firmware_version)
500                                 / CD1400_PPR_PRESCALER, 1000));
501
502                 for (cdu = 0; cdu < CD1400_NO_OF_CHANNELS; ++cdu, ++unit) {
503                         struct com_s    *com;
504
505         com = kmalloc(sizeof *com, M_DEVBUF, M_WAITOK | M_ZERO);
506         com->unit = unit;
507                         callout_init_mp(&com->dtr_ch);
508                         com->gfrcr_image = firmware_version;
509                         if (CY_RTS_DTR_SWAPPED(firmware_version)) {
510                                 com->mcr_dtr = MCR_RTS;
511                                 com->mcr_rts = MCR_DTR;
512                                 com->mcr_rts_reg = CD1400_MSVR2;
513                         } else {
514                                 com->mcr_dtr = MCR_DTR;
515                                 com->mcr_rts = MCR_RTS;
516                                 com->mcr_rts_reg = CD1400_MSVR1;
517                         }
518         com->dtr_wait = 3 * hz;
519         com->obufs[0].l_head = com->obuf1;
520         com->obufs[1].l_head = com->obuf2;
521
522                         com->cy_align = cy_align;
523                         com->cy_iobase = cy_iobase;
524         com->iobase = iobase;
525                         com->car = ~CD1400_CAR_CHAN;
526
527         /*
528          * We don't use all the flags from <sys/ttydefaults.h> since they
529          * are only relevant for logins.  It's important to have echo off
530          * initially so that the line doesn't start blathering before the
531          * echo flag can be turned off.
532          */
533         com->it_in.c_iflag = 0;
534         com->it_in.c_oflag = 0;
535         com->it_in.c_cflag = TTYDEF_CFLAG;
536         com->it_in.c_lflag = 0;
537         if (unit == comconsole) {
538                 com->it_in.c_iflag = TTYDEF_IFLAG;
539                 com->it_in.c_oflag = TTYDEF_OFLAG;
540                 com->it_in.c_cflag = TTYDEF_CFLAG | CLOCAL;
541                 com->it_in.c_lflag = TTYDEF_LFLAG;
542                 com->lt_out.c_cflag = com->lt_in.c_cflag = CLOCAL;
543         }
544         if (siosetwater(com, com->it_in.c_ispeed) != 0) {
545                 enable_intr();
546                 kfree(com, M_DEVBUF);
547                 return (0);
548         }
549         enable_intr();
550         termioschars(&com->it_in);
551         com->it_in.c_ispeed = com->it_in.c_ospeed = comdefaultrate;
552         com->it_out = com->it_in;
553
554         crit_enter();
555         com_addr(unit) = com;
556         crit_exit();
557
558         if (!sio_registered) {
559                 callout_init_mp(&sio_timeout_handle);
560                 register_swi_mp(SWI_TTY, siopoll, NULL, "cy", NULL, -1);
561                 sio_registered = TRUE;
562         }
563         minorbase = UNIT_TO_MINOR(unit);
564         make_dev(&sio_ops, minorbase,
565                 UID_ROOT, GID_WHEEL, 0600, "ttyc%r%r", adapter,
566                 unit % CY_MAX_PORTS);
567         make_dev(&sio_ops, minorbase | CONTROL_INIT_STATE,
568                 UID_ROOT, GID_WHEEL, 0600, "ttyic%r%r", adapter,
569                 unit % CY_MAX_PORTS);
570         make_dev(&sio_ops, minorbase | CONTROL_LOCK_STATE,
571                 UID_ROOT, GID_WHEEL, 0600, "ttylc%r%r", adapter,
572                 unit % CY_MAX_PORTS);
573         make_dev(&sio_ops, minorbase | CALLOUT_MASK,
574                 UID_UUCP, GID_DIALER, 0660, "cuac%r%r", adapter,
575                 unit % CY_MAX_PORTS);
576         make_dev(&sio_ops, minorbase | CALLOUT_MASK | CONTROL_INIT_STATE,
577                 UID_UUCP, GID_DIALER, 0660, "cuaic%r%r", adapter,
578                 unit % CY_MAX_PORTS);
579         make_dev(&sio_ops, minorbase | CALLOUT_MASK | CONTROL_LOCK_STATE,
580                 UID_UUCP, GID_DIALER, 0660, "cualc%r%r", adapter,
581                 unit % CY_MAX_PORTS);
582
583         /* for(cdu...), for(cyu...) terminating blocks */
584                 }
585         }
586
587         /* ensure an edge for the next interrupt */
588         cy_outb(cy_iobase, CY_CLEAR_INTR, cy_align, 0);
589
590         return (adapter);
591 }
592
593 static int
594 sioopen(struct dev_open_args *ap)
595 {
596         cdev_t dev = ap->a_head.a_dev;
597         struct com_s    *com;
598         int             error;
599         int             mynor;
600         struct tty      *tp;
601         int             unit;
602
603         mynor = minor(dev);
604         unit = MINOR_TO_UNIT(mynor);
605         if ((u_int) unit >= NSIO || (com = com_addr(unit)) == NULL)
606                 return (ENXIO);
607         if (mynor & CONTROL_MASK)
608                 return (0);
609
610         lwkt_gettoken(&tty_token);
611 #if 0 /* XXX */
612         tp = com->tp = sio_tty[unit] = ttymalloc(sio_tty[unit]);
613 #else
614         tp = com->tp = &sio_tty[unit];
615 #endif
616         dev->si_tty = tp;
617         crit_enter();
618         /*
619          * We jump to this label after all non-interrupted sleeps to pick
620          * up any changes of the device state.
621          */
622 open_top:
623         while (com->state & CS_DTR_OFF) {
624                 error = tsleep(&com->dtr_wait, PCATCH, "cydtr", 0);
625                 if (error != 0)
626                         goto out;
627         }
628         if (tp->t_state & TS_ISOPEN) {
629                 /*
630                  * The device is open, so everything has been initialized.
631                  * Handle conflicts.
632                  */
633                 if (mynor & CALLOUT_MASK) {
634                         if (!com->active_out) {
635                                 error = EBUSY;
636                                 goto out;
637                         }
638                 } else {
639                         if (com->active_out) {
640                                 if (ap->a_oflags & O_NONBLOCK) {
641                                         error = EBUSY;
642                                         goto out;
643                                 }
644                                 error = tsleep(&com->active_out,
645                                                PCATCH, "cybi", 0);
646                                 if (error != 0)
647                                         goto out;
648                                 goto open_top;
649                         }
650                 }
651                 if (tp->t_state & TS_XCLUDE &&
652                     priv_check_cred(ap->a_cred, PRIV_ROOT, 0)) {
653                         error = EBUSY;
654                         goto out;
655                 }
656         } else {
657                 /*
658                  * The device isn't open, so there are no conflicts.
659                  * Initialize it.  Initialization is done twice in many
660                  * cases: to preempt sleeping callin opens if we are
661                  * callout, and to complete a callin open after DCD rises.
662                  */
663                 tp->t_oproc = comstart;
664                 tp->t_stop = comstop;
665                 tp->t_param = comparam;
666                 tp->t_dev = dev;
667                 tp->t_termios = mynor & CALLOUT_MASK
668                                 ? com->it_out : com->it_in;
669
670                 /* Encode per-board unit in LIVR for access in intr routines. */
671                 cd_setreg(com, CD1400_LIVR,
672                           (unit & CD1400_xIVR_CHAN) << CD1400_xIVR_CHAN_SHIFT);
673
674                 (void)commctl(com, TIOCM_DTR | TIOCM_RTS, DMSET);
675 #if 0
676                 com->poll = com->no_irq;
677                 com->poll_output = com->loses_outints;
678 #endif
679                 ++com->wopeners;
680                 error = comparam(tp, &tp->t_termios);
681                 --com->wopeners;
682                 if (error != 0)
683                         goto out;
684 #if 0
685                 if (com->hasfifo) {
686                         /*
687                          * (Re)enable and flush fifos.
688                          *
689                          * Certain SMC chips cause problems if the fifos
690                          * are enabled while input is ready.  Turn off the
691                          * fifo if necessary to clear the input.  We test
692                          * the input ready bit after enabling the fifos
693                          * since we've already enabled them in comparam()
694                          * and to handle races between enabling and fresh
695                          * input.
696                          */
697                         while (TRUE) {
698                                 outb(iobase + com_fifo,
699                                      FIFO_RCV_RST | FIFO_XMT_RST
700                                      | com->fifo_image);
701                                 DELAY(100);
702                                 if (!(inb(com->line_status_port) & LSR_RXRDY))
703                                         break;
704                                 outb(iobase + com_fifo, 0);
705                                 DELAY(100);
706                                 (void) inb(com->data_port);
707                         }
708                 }
709
710                 disable_intr();
711                 (void) inb(com->line_status_port);
712                 (void) inb(com->data_port);
713                 com->prev_modem_status = com->last_modem_status
714                     = inb(com->modem_status_port);
715                 outb(iobase + com_ier, IER_ERXRDY | IER_ETXRDY | IER_ERLS
716                                        | IER_EMSC);
717                 enable_intr();
718 #else /* !0 */
719                 /*
720                  * Flush fifos.  This requires a full channel reset which
721                  * also disables the transmitter and receiver.  Recover
722                  * from this.
723                  */
724                 cd1400_channel_cmd(com,
725                                    CD1400_CCR_CMDRESET | CD1400_CCR_CHANRESET);
726                 cd1400_channel_cmd(com, com->channel_control);
727
728                 disable_intr();
729                 com->prev_modem_status = com->last_modem_status
730                     = cd_getreg(com, CD1400_MSVR2);
731                 cd_setreg(com, CD1400_SRER,
732                           com->intr_enable
733                           = CD1400_SRER_MDMCH | CD1400_SRER_RXDATA);
734                 enable_intr();
735 #endif /* 0 */
736                 /*
737                  * Handle initial DCD.  Callout devices get a fake initial
738                  * DCD (trapdoor DCD).  If we are callout, then any sleeping
739                  * callin opens get woken up and resume sleeping on "cybi"
740                  * instead of "cydcd".
741                  */
742                 /*
743                  * XXX `mynor & CALLOUT_MASK' should be
744                  * `tp->t_cflag & (SOFT_CARRIER | TRAPDOOR_CARRIER) where
745                  * TRAPDOOR_CARRIER is the default initial state for callout
746                  * devices and SOFT_CARRIER is like CLOCAL except it hides
747                  * the true carrier.
748                  */
749                 if (com->prev_modem_status & MSR_DCD || mynor & CALLOUT_MASK)
750                         (*linesw[tp->t_line].l_modem)(tp, 1);
751         }
752         /*
753          * Wait for DCD if necessary.
754          */
755         if (!(tp->t_state & TS_CARR_ON) && !(mynor & CALLOUT_MASK)
756             && !(tp->t_cflag & CLOCAL) && !(ap->a_oflags & O_NONBLOCK)) {
757                 ++com->wopeners;
758                 error = tsleep(TSA_CARR_ON(tp), PCATCH, "cydcd", 0);
759                 --com->wopeners;
760                 if (error != 0)
761                         goto out;
762                 goto open_top;
763         }
764         error = (*linesw[tp->t_line].l_open)(dev, tp);
765         disc_optim(tp, &tp->t_termios, com);
766         if (tp->t_state & TS_ISOPEN && mynor & CALLOUT_MASK)
767                 com->active_out = TRUE;
768         siosettimeout();
769 out:
770         crit_exit();
771         if (!(tp->t_state & TS_ISOPEN) && com->wopeners == 0)
772                 comhardclose(com);
773         lwkt_reltoken(&tty_token);
774         return (error);
775 }
776
777 /*
778  * NOTE: Must be called with tty_token held
779  */
780 static int
781 sioclose(struct dev_close_args *ap)
782 {
783         cdev_t dev = ap->a_head.a_dev;
784         struct com_s    *com;
785         int             mynor;
786         struct tty      *tp;
787
788         ASSERT_LWKT_TOKEN_HELD(&tty_token);
789         mynor = minor(dev);
790         if (mynor & CONTROL_MASK)
791                 return (0);
792         lwkt_gettoken(&tty_token);
793         com = com_addr(MINOR_TO_UNIT(mynor));
794         tp = com->tp;
795         crit_enter();
796         cd_etc(com, CD1400_ETC_STOPBREAK);
797         (*linesw[tp->t_line].l_close)(tp, ap->a_fflag);
798         disc_optim(tp, &tp->t_termios, com);
799         comstop(tp, FREAD | FWRITE);
800         comhardclose(com);
801         ttyclose(tp);
802         siosettimeout();
803         crit_exit();
804 #ifdef broken /* session holds a ref to the tty; can't deallocate */
805         ttyfree(tp);
806         com->tp = sio_tty[unit] = NULL;
807 #endif
808         lwkt_reltoken(&tty_token);
809         return (0);
810 }
811
812 /*
813  * NOTE: Must be called with tty_token held
814  */
815 static void
816 comhardclose(struct com_s *com)
817 {
818         cy_addr         iobase;
819         struct tty      *tp;
820         int             unit;
821
822         ASSERT_LWKT_TOKEN_HELD(&tty_token);
823
824         unit = com->unit;
825         iobase = com->iobase;
826         crit_enter();
827 #if 0
828         com->poll = FALSE;
829         com->poll_output = FALSE;
830 #endif
831         com->do_timestamp = 0;
832 #if 0
833         outb(iobase + com_cfcr, com->cfcr_image &= ~CFCR_SBREAK);
834 #else
835         /* XXX */
836         disable_intr();
837         com->etc = ETC_NONE;
838         cd_setreg(com, CD1400_COR2, com->cor[1] &= ~CD1400_COR2_ETC);
839         enable_intr();
840         cd1400_channel_cmd(com, CD1400_CCR_CMDRESET | CD1400_CCR_FTF);
841 #endif
842
843         {
844 #if 0
845                 outb(iobase + com_ier, 0);
846 #else
847                 disable_intr();
848                 cd_setreg(com, CD1400_SRER, com->intr_enable = 0);
849                 enable_intr();
850 #endif
851                 tp = com->tp;
852                 if ((tp->t_cflag & HUPCL)
853                     /*
854                      * XXX we will miss any carrier drop between here and the
855                      * next open.  Perhaps we should watch DCD even when the
856                      * port is closed; it is not sufficient to check it at
857                      * the next open because it might go up and down while
858                      * we're not watching.
859                      */
860                     || (!com->active_out
861                        && !(com->prev_modem_status & MSR_DCD)
862                        && !(com->it_in.c_cflag & CLOCAL))
863                     || !(tp->t_state & TS_ISOPEN)) {
864                         (void)commctl(com, TIOCM_DTR, DMBIC);
865
866                         /* Disable receiver (leave transmitter enabled). */
867                         com->channel_control = CD1400_CCR_CMDCHANCTL
868                                                | CD1400_CCR_XMTEN
869                                                | CD1400_CCR_RCVDIS;
870                         cd1400_channel_cmd(com, com->channel_control);
871
872                         if (com->dtr_wait != 0 && !(com->state & CS_DTR_OFF)) {
873                                 callout_reset(&com->dtr_ch, com->dtr_wait,
874                                                 siodtrwakeup, com);
875                                 com->state |= CS_DTR_OFF;
876                         }
877                 }
878         }
879 #if 0
880         if (com->hasfifo) {
881                 /*
882                  * Disable fifos so that they are off after controlled
883                  * reboots.  Some BIOSes fail to detect 16550s when the
884                  * fifos are enabled.
885                  */
886                 outb(iobase + com_fifo, 0);
887         }
888 #endif
889         com->active_out = FALSE;
890         wakeup(&com->active_out);
891         wakeup(TSA_CARR_ON(tp));        /* restart any wopeners */
892         crit_exit();
893 }
894
895 static int
896 siowrite(struct dev_write_args *ap)
897 {
898         cdev_t dev = ap->a_head.a_dev;
899         struct uio *uio = ap->a_uio;
900         int             mynor;
901         struct tty      *tp;
902         int             unit;
903
904         mynor = minor(dev);
905         if (mynor & CONTROL_MASK)
906                 return (ENODEV);
907
908         lwkt_gettoken(&tty_token);
909         unit = MINOR_TO_UNIT(mynor);
910         tp = com_addr(unit)->tp;
911         /*
912          * (XXX) We disallow virtual consoles if the physical console is
913          * a serial port.  This is in case there is a display attached that
914          * is not the console.  In that situation we don't need/want the X
915          * server taking over the console.
916          */
917         if (constty != NULL && unit == comconsole)
918                 constty = NULL;
919 #ifdef Smarts
920         /* XXX duplicate ttwrite(), but without so much output processing on
921          * CR & LF chars.  Hardly worth the effort, given that high-throughput
922          * sessions are raw anyhow.
923          */
924 #else
925         return ((*linesw[tp->t_line].l_write)(tp, uio, ap->a_ioflag));
926 #endif
927         lwkt_reltoken(&tty_token);
928 }
929
930 static void
931 siodtrwakeup(void *chan)
932 {
933         struct com_s    *com;
934
935         lwkt_gettoken(&tty_token);
936         com = (struct com_s *)chan;
937         com->state &= ~CS_DTR_OFF;
938         wakeup(&com->dtr_wait);
939         lwkt_reltoken(&tty_token);
940 }
941
942 /*
943  * NOTE: Must be called with tty_token held
944  */
945 static void
946 sioinput(struct com_s *com)
947 {
948         u_char          *buf;
949         int             incc;
950         u_char          line_status;
951         int             recv_data;
952         struct tty      *tp;
953
954         ASSERT_LWKT_TOKEN_HELD(&tty_token);
955
956         buf = com->ibuf;
957         tp = com->tp;
958         if (!(tp->t_state & TS_ISOPEN)) {
959                 com_events -= (com->iptr - com->ibuf);
960                 com->iptr = com->ibuf;
961                 return;
962         }
963         if (tp->t_state & TS_CAN_BYPASS_L_RINT) {
964                 /*
965                  * Avoid the grotesquely inefficient lineswitch routine
966                  * (ttyinput) in "raw" mode.  It usually takes about 450
967                  * instructions (that's without canonical processing or echo!).
968                  * slinput is reasonably fast (usually 40 instructions plus
969                  * call overhead).
970                  */
971                 do {
972                         enable_intr();
973                         incc = com->iptr - buf;
974                         if (tp->t_rawq.c_cc + incc > tp->t_ihiwat
975                             && (com->state & CS_RTS_IFLOW
976                                 || tp->t_iflag & IXOFF)
977                             && !(tp->t_state & TS_TBLOCK))
978                                 ttyblock(tp);
979                         com->delta_error_counts[CE_TTY_BUF_OVERFLOW]
980                                 += b_to_q((char *)buf, incc, &tp->t_rawq);
981                         buf += incc;
982                         tk_nin += incc;
983                         tk_rawcc += incc;
984                         tp->t_rawcc += incc;
985                         ttwakeup(tp);
986                         if (tp->t_state & TS_TTSTOP
987                             && (tp->t_iflag & IXANY
988                                 || tp->t_cc[VSTART] == tp->t_cc[VSTOP])) {
989                                 tp->t_state &= ~TS_TTSTOP;
990                                 tp->t_lflag &= ~FLUSHO;
991                                 comstart(tp);
992                         }
993                         disable_intr();
994                 } while (buf < com->iptr);
995         } else {
996                 do {
997                         enable_intr();
998                         line_status = buf[com->ierroff];
999                         recv_data = *buf++;
1000                         if (line_status
1001                             & (LSR_BI | LSR_FE | LSR_OE | LSR_PE)) {
1002                                 if (line_status & LSR_BI)
1003                                         recv_data |= TTY_BI;
1004                                 if (line_status & LSR_FE)
1005                                         recv_data |= TTY_FE;
1006                                 if (line_status & LSR_OE)
1007                                         recv_data |= TTY_OE;
1008                                 if (line_status & LSR_PE)
1009                                         recv_data |= TTY_PE;
1010                         }
1011                         (*linesw[tp->t_line].l_rint)(recv_data, tp);
1012                         disable_intr();
1013                 } while (buf < com->iptr);
1014         }
1015         com_events -= (com->iptr - com->ibuf);
1016         com->iptr = com->ibuf;
1017
1018         /*
1019          * There is now room for another low-level buffer full of input,
1020          * so enable RTS if it is now disabled and there is room in the
1021          * high-level buffer.
1022          */
1023         if ((com->state & CS_RTS_IFLOW) && !(com->mcr_image & com->mcr_rts) &&
1024             !(tp->t_state & TS_TBLOCK))
1025 #if 0
1026                 outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
1027 #else
1028                 cd_setreg(com, com->mcr_rts_reg,
1029                           com->mcr_image |= com->mcr_rts);
1030 #endif
1031 }
1032
1033 void
1034 siointr(void *arg)
1035 {
1036         int     unit = (int)arg;
1037         int     baseu;
1038         int     cy_align;
1039         cy_addr cy_iobase;
1040         int     cyu;
1041         cy_addr iobase;
1042         u_char  status;
1043
1044         lwkt_gettoken(&tty_token);
1045         com_lock();     /* XXX could this be placed down lower in the loop? */
1046
1047         baseu = unit * CY_MAX_PORTS;
1048         cy_align = com_addr(baseu)->cy_align;
1049         cy_iobase = com_addr(baseu)->cy_iobase;
1050
1051         /* check each CD1400 in turn */
1052         for (cyu = 0; cyu < cy_nr_cd1400s[unit]; ++cyu) {
1053                 iobase = (cy_addr) (cy_iobase
1054                                     + (cy_chip_offset[cyu] << cy_align));
1055                 /* poll to see if it has any work */
1056                 status = cd_inb(iobase, CD1400_SVRR, cy_align);
1057                 if (status == 0)
1058                         continue;
1059 #ifdef CyDebug
1060                 ++cy_svrr_probes;
1061 #endif
1062                 /* service requests as appropriate, giving priority to RX */
1063                 if (status & CD1400_SVRR_RXRDY) {
1064                         struct com_s    *com;
1065                         u_int           count;
1066                         u_char          *ioptr;
1067                         u_char          line_status;
1068                         u_char          recv_data;
1069                         u_char          serv_type;
1070 #ifdef PollMode
1071                         u_char          save_rir;
1072 #endif
1073
1074 #ifdef PollMode
1075                         save_rir = cd_inb(iobase, CD1400_RIR, cy_align);
1076
1077                         /* enter rx service */
1078                         cd_outb(iobase, CD1400_CAR, cy_align, save_rir);
1079                         com_addr(baseu + cyu * CD1400_NO_OF_CHANNELS)->car
1080                         = save_rir & CD1400_CAR_CHAN;
1081
1082                         serv_type = cd_inb(iobase, CD1400_RIVR, cy_align);
1083                         com = com_addr(baseu
1084                                        + ((serv_type >> CD1400_xIVR_CHAN_SHIFT)
1085                                           & CD1400_xIVR_CHAN));
1086 #else
1087                         /* ack receive service */
1088                         serv_type = cy_inb(iobase, CY8_SVCACKR, cy_align);
1089
1090                         com = com_addr(baseu +
1091                                        + ((serv_type >> CD1400_xIVR_CHAN_SHIFT)
1092                                           & CD1400_xIVR_CHAN));
1093 #endif
1094
1095                 if (serv_type & CD1400_RIVR_EXCEPTION) {
1096                         ++com->recv_exception;
1097                         line_status = cd_inb(iobase, CD1400_RDSR, cy_align);
1098                         /* break/unnattached error bits or real input? */
1099                         recv_data = cd_inb(iobase, CD1400_RDSR, cy_align);
1100 #ifndef SOFT_HOTCHAR
1101                         if (line_status & CD1400_RDSR_SPECIAL
1102                             && com->hotchar != 0)
1103                                 setsofttty();
1104 #endif
1105 #if 1 /* XXX "intelligent" PFO error handling would break O error handling */
1106                         if (line_status & (LSR_PE|LSR_FE|LSR_BI)) {
1107                                 /*
1108                                   Don't store PE if IGNPAR and BI if IGNBRK,
1109                                   this hack allows "raw" tty optimization
1110                                   works even if IGN* is set.
1111                                 */
1112                                 if (   com->tp == NULL
1113                                     || !(com->tp->t_state & TS_ISOPEN)
1114                                     || ((line_status & (LSR_PE|LSR_FE))
1115                                     &&  (com->tp->t_iflag & IGNPAR))
1116                                     || ((line_status & LSR_BI)
1117                                     &&  (com->tp->t_iflag & IGNBRK)))
1118                                         goto cont;
1119                                 if (   (line_status & (LSR_PE|LSR_FE))
1120                                     && (com->tp->t_state & TS_CAN_BYPASS_L_RINT)
1121                                     && ((line_status & LSR_FE)
1122                                     ||  ((line_status & LSR_PE)
1123                                     &&  (com->tp->t_iflag & INPCK))))
1124                                         recv_data = 0;
1125                         }
1126 #endif /* 1 */
1127                         ++com->bytes_in;
1128 #ifdef SOFT_HOTCHAR
1129                         if (com->hotchar != 0 && recv_data == com->hotchar)
1130                                 setsofttty();
1131 #endif
1132                         ioptr = com->iptr;
1133                         if (ioptr >= com->ibufend)
1134                                 CE_RECORD(com, CE_INTERRUPT_BUF_OVERFLOW);
1135                         else {
1136                                 if (com->do_timestamp)
1137                                         microtime(&com->timestamp);
1138                                 ++com_events;
1139                                 ioptr[0] = recv_data;
1140                                 ioptr[com->ierroff] = line_status;
1141                                 com->iptr = ++ioptr;
1142                                 if (ioptr == com->ihighwater
1143                                     && com->state & CS_RTS_IFLOW)
1144 #if 0
1145                                         outb(com->modem_ctl_port,
1146                                              com->mcr_image &= ~MCR_RTS);
1147 #else
1148                                         cd_outb(iobase, com->mcr_rts_reg,
1149                                                 cy_align,
1150                                                 com->mcr_image &=
1151                                                 ~com->mcr_rts);
1152 #endif
1153                                 if (line_status & LSR_OE)
1154                                         CE_RECORD(com, CE_OVERRUN);
1155                         }
1156                         goto cont;
1157                 } else {
1158                         int     ifree;
1159
1160                         count = cd_inb(iobase, CD1400_RDCR, cy_align);
1161                         if (!count)
1162                                 goto cont;
1163                         com->bytes_in += count;
1164                         ioptr = com->iptr;
1165                         ifree = com->ibufend - ioptr;
1166                         if (count > ifree) {
1167                                 count -= ifree;
1168                                 com_events += ifree;
1169                                 if (ifree != 0) {
1170                                         if (com->do_timestamp)
1171                                                 microtime(&com->timestamp);
1172                                         do {
1173                                                 recv_data = cd_inb(iobase,
1174                                                                    CD1400_RDSR,
1175                                                                    cy_align);
1176 #ifdef SOFT_HOTCHAR
1177                                                 if (com->hotchar != 0
1178                                                     && recv_data
1179                                                        == com->hotchar)
1180                                                         setsofttty();
1181 #endif
1182                                                 ioptr[0] = recv_data;
1183                                                 ioptr[com->ierroff] = 0;
1184                                                 ++ioptr;
1185                                         } while (--ifree != 0);
1186                                 }
1187                                 com->delta_error_counts
1188                                     [CE_INTERRUPT_BUF_OVERFLOW] += count;
1189                                 do {
1190                                         recv_data = cd_inb(iobase, CD1400_RDSR,
1191                                                            cy_align);
1192 #ifdef SOFT_HOTCHAR
1193                                         if (com->hotchar != 0
1194                                             && recv_data == com->hotchar)
1195                                                 setsofttty();
1196 #endif
1197                                 } while (--count != 0);
1198                         } else {
1199                                 if (com->do_timestamp)
1200                                         microtime(&com->timestamp);
1201                                 if (ioptr <= com->ihighwater
1202                                     && ioptr + count > com->ihighwater
1203                                     && com->state & CS_RTS_IFLOW)
1204 #if 0
1205                                         outb(com->modem_ctl_port,
1206                                              com->mcr_image &= ~MCR_RTS);
1207 #else
1208                                         cd_outb(iobase, com->mcr_rts_reg,
1209                                                 cy_align,
1210                                                 com->mcr_image
1211                                                 &= ~com->mcr_rts);
1212 #endif
1213                                 com_events += count;
1214                                 do {
1215                                         recv_data = cd_inb(iobase, CD1400_RDSR,
1216                                                            cy_align);
1217 #ifdef SOFT_HOTCHAR
1218                                         if (com->hotchar != 0
1219                                             && recv_data == com->hotchar)
1220                                                 setsofttty();
1221 #endif
1222                                         ioptr[0] = recv_data;
1223                                         ioptr[com->ierroff] = 0;
1224                                         ++ioptr;
1225                                 } while (--count != 0);
1226                         }
1227                         com->iptr = ioptr;
1228                 }
1229 cont:
1230
1231                         /* terminate service context */
1232 #ifdef PollMode
1233                         cd_outb(iobase, CD1400_RIR, cy_align,
1234                                 save_rir
1235                                 & ~(CD1400_RIR_RDIREQ | CD1400_RIR_RBUSY));
1236 #else
1237                         cd_outb(iobase, CD1400_EOSRR, cy_align, 0);
1238 #endif
1239                 }
1240                 if (status & CD1400_SVRR_MDMCH) {
1241                         struct com_s    *com;
1242                         u_char  modem_status;
1243 #ifdef PollMode
1244                         u_char  save_mir;
1245 #else
1246                         u_char  vector;
1247 #endif
1248
1249 #ifdef PollMode
1250                         save_mir = cd_inb(iobase, CD1400_MIR, cy_align);
1251
1252                         /* enter modem service */
1253                         cd_outb(iobase, CD1400_CAR, cy_align, save_mir);
1254                         com_addr(baseu + cyu * CD1400_NO_OF_CHANNELS)->car
1255                         = save_mir & CD1400_CAR_CHAN;
1256
1257                         com = com_addr(baseu + cyu * CD1400_NO_OF_CHANNELS
1258                                        + (save_mir & CD1400_MIR_CHAN));
1259 #else
1260                         /* ack modem service */
1261                         vector = cy_inb(iobase, CY8_SVCACKM, cy_align);
1262
1263                         com = com_addr(baseu
1264                                        + ((vector >> CD1400_xIVR_CHAN_SHIFT)
1265                                           & CD1400_xIVR_CHAN));
1266 #endif
1267                         ++com->mdm;
1268                         modem_status = cd_inb(iobase, CD1400_MSVR2, cy_align);
1269                 if (modem_status != com->last_modem_status) {
1270                         if (com->do_dcd_timestamp
1271                             && !(com->last_modem_status & MSR_DCD)
1272                             && modem_status & MSR_DCD)
1273                                 microtime(&com->dcd_timestamp);
1274
1275                         /*
1276                          * Schedule high level to handle DCD changes.  Note
1277                          * that we don't use the delta bits anywhere.  Some
1278                          * UARTs mess them up, and it's easy to remember the
1279                          * previous bits and calculate the delta.
1280                          */
1281                         com->last_modem_status = modem_status;
1282                         if (!(com->state & CS_CHECKMSR)) {
1283                                 com_events += LOTS_OF_EVENTS;
1284                                 com->state |= CS_CHECKMSR;
1285                                 setsofttty();
1286                         }
1287
1288 #ifdef SOFT_CTS_OFLOW
1289                         /* handle CTS change immediately for crisp flow ctl */
1290                         if (com->state & CS_CTS_OFLOW) {
1291                                 if (modem_status & MSR_CTS) {
1292                                         com->state |= CS_ODEVREADY;
1293                                         if (com->state >= (CS_BUSY | CS_TTGO
1294                                                            | CS_ODEVREADY)
1295                                             && !(com->intr_enable
1296                                                  & CD1400_SRER_TXRDY))
1297                                                 cd_outb(iobase, CD1400_SRER,
1298                                                         cy_align,
1299                                                         com->intr_enable
1300                                                         = com->intr_enable
1301                                                           & ~CD1400_SRER_TXMPTY
1302                                                           | CD1400_SRER_TXRDY);
1303                                 } else {
1304                                         com->state &= ~CS_ODEVREADY;
1305                                         if (com->intr_enable
1306                                             & CD1400_SRER_TXRDY)
1307                                                 cd_outb(iobase, CD1400_SRER,
1308                                                         cy_align,
1309                                                         com->intr_enable
1310                                                         = com->intr_enable
1311                                                           & ~CD1400_SRER_TXRDY
1312                                                           | CD1400_SRER_TXMPTY);
1313                                 }
1314                         }
1315 #endif
1316                 }
1317
1318                         /* terminate service context */
1319 #ifdef PollMode
1320                         cd_outb(iobase, CD1400_MIR, cy_align,
1321                                 save_mir
1322                                 & ~(CD1400_MIR_RDIREQ | CD1400_MIR_RBUSY));
1323 #else
1324                         cd_outb(iobase, CD1400_EOSRR, cy_align, 0);
1325 #endif
1326                 }
1327                 if (status & CD1400_SVRR_TXRDY) {
1328                         struct com_s    *com;
1329 #ifdef PollMode
1330                         u_char  save_tir;
1331 #else
1332                         u_char  vector;
1333 #endif
1334
1335 #ifdef PollMode
1336                         save_tir = cd_inb(iobase, CD1400_TIR, cy_align);
1337
1338                         /* enter tx service */
1339                         cd_outb(iobase, CD1400_CAR, cy_align, save_tir);
1340                         com_addr(baseu + cyu * CD1400_NO_OF_CHANNELS)->car
1341                         = save_tir & CD1400_CAR_CHAN;
1342
1343                         com = com_addr(baseu
1344                                        + cyu * CD1400_NO_OF_CHANNELS
1345                                        + (save_tir & CD1400_TIR_CHAN));
1346 #else
1347                         /* ack transmit service */
1348                         vector = cy_inb(iobase, CY8_SVCACKT, cy_align);
1349
1350                         com = com_addr(baseu
1351                                        + ((vector >> CD1400_xIVR_CHAN_SHIFT)
1352                                           & CD1400_xIVR_CHAN));
1353 #endif
1354
1355                         if (com->etc != ETC_NONE) {
1356                                 if (com->intr_enable & CD1400_SRER_TXRDY) {
1357                                         /*
1358                                          * Here due to sloppy SRER_TXRDY
1359                                          * enabling.  Ignore.  Come back when
1360                                          * tx is empty.
1361                                          */
1362                                         cd_outb(iobase, CD1400_SRER, cy_align,
1363                                                 com->intr_enable
1364                                                 = (com->intr_enable
1365                                                   & ~CD1400_SRER_TXRDY)
1366                                                   | CD1400_SRER_TXMPTY);
1367                                         goto terminate_tx_service;
1368                                 }
1369                                 switch (com->etc) {
1370                                 case CD1400_ETC_SENDBREAK:
1371                                 case CD1400_ETC_STOPBREAK:
1372                                         /*
1373                                          * Start the command.  Come back on
1374                                          * next tx empty interrupt, hopefully
1375                                          * after command has been executed.
1376                                          */
1377                                         cd_outb(iobase, CD1400_COR2, cy_align,
1378                                                 com->cor[1] |= CD1400_COR2_ETC);
1379                                         cd_outb(iobase, CD1400_TDR, cy_align,
1380                                                 CD1400_ETC_CMD);
1381                                         cd_outb(iobase, CD1400_TDR, cy_align,
1382                                                 com->etc);
1383                                         if (com->etc == CD1400_ETC_SENDBREAK)
1384                                                 com->etc = ETC_BREAK_STARTING;
1385                                         else
1386                                                 com->etc = ETC_BREAK_ENDING;
1387                                         goto terminate_tx_service;
1388                                 case ETC_BREAK_STARTING:
1389                                         /*
1390                                          * BREAK is now on.  Continue with
1391                                          * SRER_TXMPTY processing, hopefully
1392                                          * don't come back.
1393                                          */
1394                                         com->etc = ETC_BREAK_STARTED;
1395                                         break;
1396                                 case ETC_BREAK_STARTED:
1397                                         /*
1398                                          * Came back due to sloppy SRER_TXMPTY
1399                                          * enabling.  Hope again.
1400                                          */
1401                                         break;
1402                                 case ETC_BREAK_ENDING:
1403                                         /*
1404                                          * BREAK is now off.  Continue with
1405                                          * SRER_TXMPTY processing and don't
1406                                          * come back.  The SWI handler will
1407                                          * restart tx interrupts if necessary.
1408                                          */
1409                                         cd_outb(iobase, CD1400_COR2, cy_align,
1410                                                 com->cor[1]
1411                                                 &= ~CD1400_COR2_ETC);
1412                                         com->etc = ETC_BREAK_ENDED;
1413                                         if (!(com->state & CS_ODONE)) {
1414                                                 com_events += LOTS_OF_EVENTS;
1415                                                 com->state |= CS_ODONE;
1416                                                 setsofttty();
1417                                         }
1418                                         break;
1419                                 case ETC_BREAK_ENDED:
1420                                         /*
1421                                          * Shouldn't get here.  Hope again.
1422                                          */
1423                                         break;
1424                                 }
1425                         }
1426                         if (com->intr_enable & CD1400_SRER_TXMPTY) {
1427                                 if (!(com->extra_state & CSE_ODONE)) {
1428                                         com_events += LOTS_OF_EVENTS;
1429                                         com->extra_state |= CSE_ODONE;
1430                                         setsofttty();
1431                                 }
1432                                 cd_outb(iobase, CD1400_SRER, cy_align,
1433                                         com->intr_enable
1434                                         &= ~CD1400_SRER_TXMPTY);
1435                                 goto terminate_tx_service;
1436                         }
1437                 if (com->state >= (CS_BUSY | CS_TTGO | CS_ODEVREADY)) {
1438                         u_char  *ioptr;
1439                         u_int   ocount;
1440
1441                         ioptr = com->obufq.l_head;
1442                                 ocount = com->obufq.l_tail - ioptr;
1443                                 if (ocount > CD1400_TX_FIFO_SIZE)
1444                                         ocount = CD1400_TX_FIFO_SIZE;
1445                                 com->bytes_out += ocount;
1446                                 do
1447                                         cd_outb(iobase, CD1400_TDR, cy_align,
1448                                                 *ioptr++);
1449                                 while (--ocount != 0);
1450                         com->obufq.l_head = ioptr;
1451                         if (ioptr >= com->obufq.l_tail) {
1452                                 struct lbq      *qp;
1453
1454                                 qp = com->obufq.l_next;
1455                                 qp->l_queued = FALSE;
1456                                 qp = qp->l_next;
1457                                 if (qp != NULL) {
1458                                         com->obufq.l_head = qp->l_head;
1459                                         com->obufq.l_tail = qp->l_tail;
1460                                         com->obufq.l_next = qp;
1461                                 } else {
1462                                         /* output just completed */
1463                                         com->state &= ~CS_BUSY;
1464
1465                                         /*
1466                                          * The setting of CSE_ODONE may be
1467                                          * stale here.  We currently only
1468                                          * use it when CS_BUSY is set, and
1469                                          * fixing it when we clear CS_BUSY
1470                                          * is easiest.
1471                                          */
1472                                         if (com->extra_state & CSE_ODONE) {
1473                                                 com_events -= LOTS_OF_EVENTS;
1474                                                 com->extra_state &= ~CSE_ODONE;
1475                                         }
1476
1477                                         cd_outb(iobase, CD1400_SRER, cy_align,
1478                                                 com->intr_enable
1479                                                 = (com->intr_enable
1480                                                   & ~CD1400_SRER_TXRDY)
1481                                                   | CD1400_SRER_TXMPTY);
1482                                 }
1483                                 if (!(com->state & CS_ODONE)) {
1484                                         com_events += LOTS_OF_EVENTS;
1485                                         com->state |= CS_ODONE;
1486
1487                                         /* handle at high level ASAP */
1488                                         setsofttty();
1489                                 }
1490                         }
1491                 }
1492
1493                         /* terminate service context */
1494 terminate_tx_service:
1495 #ifdef PollMode
1496                         cd_outb(iobase, CD1400_TIR, cy_align,
1497                                 save_tir
1498                                 & ~(CD1400_TIR_RDIREQ | CD1400_TIR_RBUSY));
1499 #else
1500                         cd_outb(iobase, CD1400_EOSRR, cy_align, 0);
1501 #endif
1502                 }
1503         }
1504
1505         /* ensure an edge for the next interrupt */
1506         cy_outb(cy_iobase, CY_CLEAR_INTR, cy_align, 0);
1507
1508         schedsofttty();
1509
1510         com_unlock();
1511         lwkt_reltoken(&tty_token);
1512 }
1513
1514 #if 0
1515 static void
1516 siointr1(struct com_s *com)
1517 {
1518 }
1519 #endif
1520
1521 static int
1522 sioioctl(struct dev_ioctl_args *ap)
1523 {
1524         cdev_t dev = ap->a_head.a_dev;
1525         caddr_t data = ap->a_data;
1526         u_long cmd = ap->a_cmd;
1527         struct com_s    *com;
1528         int             error;
1529         int             mynor;
1530         struct tty      *tp;
1531 #if defined(COMPAT_43) || defined(COMPAT_SUNOS)
1532         int             oldcmd;
1533         struct termios  term;
1534 #endif
1535
1536         lwkt_gettoken(&tty_token);
1537         mynor = minor(dev);
1538         com = com_addr(MINOR_TO_UNIT(mynor));
1539         if (mynor & CONTROL_MASK) {
1540                 struct termios  *ct;
1541
1542                 switch (mynor & CONTROL_MASK) {
1543                 case CONTROL_INIT_STATE:
1544                         ct = mynor & CALLOUT_MASK ? &com->it_out : &com->it_in;
1545                         break;
1546                 case CONTROL_LOCK_STATE:
1547                         ct = mynor & CALLOUT_MASK ? &com->lt_out : &com->lt_in;
1548                         break;
1549                 default:
1550                         lwkt_reltoken(&tty_token);
1551                         return (ENODEV);        /* /dev/nodev */
1552                 }
1553                 switch (cmd) {
1554                 case TIOCSETA:
1555                         error = priv_check_cred(ap->a_cred, PRIV_ROOT, 0);
1556                         if (error != 0) {
1557                                 lwkt_reltoken(&tty_token);
1558                                 return (error);
1559                         }
1560                         *ct = *(struct termios *)data;
1561                         lwkt_reltoken(&tty_token);
1562                         return (0);
1563                 case TIOCGETA:
1564                         *(struct termios *)data = *ct;
1565                         lwkt_reltoken(&tty_token);
1566                         return (0);
1567                 case TIOCGETD:
1568                         *(int *)data = TTYDISC;
1569                         lwkt_reltoken(&tty_token);
1570                         return (0);
1571                 case TIOCGWINSZ:
1572                         bzero(data, sizeof(struct winsize));
1573                         lwkt_reltoken(&tty_token);
1574                         return (0);
1575                 default:
1576                         lwkt_reltoken(&tty_token);
1577                         return (ENOTTY);
1578                 }
1579         }
1580         tp = com->tp;
1581 #if defined(COMPAT_43) || defined(COMPAT_SUNOS)
1582         term = tp->t_termios;
1583         oldcmd = cmd;
1584         error = ttsetcompat(tp, &cmd, data, &term);
1585         if (error != 0) {
1586                 lwkt_reltoken(&tty_token);
1587                 return (error);
1588         }
1589         if (cmd != oldcmd)
1590                 data = (caddr_t)&term;
1591 #endif
1592         if (cmd == TIOCSETA || cmd == TIOCSETAW || cmd == TIOCSETAF) {
1593                 int     cc;
1594                 struct termios *dt = (struct termios *)data;
1595                 struct termios *lt = mynor & CALLOUT_MASK
1596                                      ? &com->lt_out : &com->lt_in;
1597
1598                 dt->c_iflag = (tp->t_iflag & lt->c_iflag)
1599                               | (dt->c_iflag & ~lt->c_iflag);
1600                 dt->c_oflag = (tp->t_oflag & lt->c_oflag)
1601                               | (dt->c_oflag & ~lt->c_oflag);
1602                 dt->c_cflag = (tp->t_cflag & lt->c_cflag)
1603                               | (dt->c_cflag & ~lt->c_cflag);
1604                 dt->c_lflag = (tp->t_lflag & lt->c_lflag)
1605                               | (dt->c_lflag & ~lt->c_lflag);
1606                 for (cc = 0; cc < NCCS; ++cc)
1607                         if (lt->c_cc[cc] != 0)
1608                                 dt->c_cc[cc] = tp->t_cc[cc];
1609                 if (lt->c_ispeed != 0)
1610                         dt->c_ispeed = tp->t_ispeed;
1611                 if (lt->c_ospeed != 0)
1612                         dt->c_ospeed = tp->t_ospeed;
1613         }
1614         error = (*linesw[tp->t_line].l_ioctl)(tp, cmd, data,
1615                                               ap->a_fflag, ap->a_cred);
1616         if (error != ENOIOCTL) {
1617                 lwkt_reltoken(&tty_token);
1618                 return (error);
1619         }
1620         crit_enter();
1621         error = ttioctl(tp, cmd, data, ap->a_fflag);
1622         disc_optim(tp, &tp->t_termios, com);
1623         if (error != ENOIOCTL) {
1624                 crit_exit();
1625                 lwkt_reltoken(&tty_token);
1626                 return (error);
1627         }
1628         switch (cmd) {
1629         case TIOCSBRK:
1630 #if 0
1631                 outb(iobase + com_cfcr, com->cfcr_image |= CFCR_SBREAK);
1632 #else
1633                 cd_etc(com, CD1400_ETC_SENDBREAK);
1634 #endif
1635                 break;
1636         case TIOCCBRK:
1637 #if 0
1638                 outb(iobase + com_cfcr, com->cfcr_image &= ~CFCR_SBREAK);
1639 #else
1640                 cd_etc(com, CD1400_ETC_STOPBREAK);
1641 #endif
1642                 break;
1643         case TIOCSDTR:
1644                 (void)commctl(com, TIOCM_DTR, DMBIS);
1645                 break;
1646         case TIOCCDTR:
1647                 (void)commctl(com, TIOCM_DTR, DMBIC);
1648                 break;
1649         /*
1650          * XXX should disallow changing MCR_RTS if CS_RTS_IFLOW is set.  The
1651          * changes get undone on the next call to comparam().
1652          */
1653         case TIOCMSET:
1654                 (void)commctl(com, *(int *)data, DMSET);
1655                 break;
1656         case TIOCMBIS:
1657                 (void)commctl(com, *(int *)data, DMBIS);
1658                 break;
1659         case TIOCMBIC:
1660                 (void)commctl(com, *(int *)data, DMBIC);
1661                 break;
1662         case TIOCMGET:
1663                 *(int *)data = commctl(com, 0, DMGET);
1664                 break;
1665         case TIOCMSDTRWAIT:
1666                 /* must be root since the wait applies to following logins */
1667                 error = priv_check_cred(ap->a_cred, PRIV_ROOT, 0);
1668                 if (error != 0) {
1669                         crit_exit();
1670                         lwkt_reltoken(&tty_token);
1671                         return (error);
1672                 }
1673                 com->dtr_wait = *(int *)data * hz / 100;
1674                 break;
1675         case TIOCMGDTRWAIT:
1676                 *(int *)data = com->dtr_wait * 100 / hz;
1677                 break;
1678         case TIOCTIMESTAMP:
1679                 com->do_timestamp = TRUE;
1680                 *(struct timeval *)data = com->timestamp;
1681                 break;
1682         case TIOCDCDTIMESTAMP:
1683                 com->do_dcd_timestamp = TRUE;
1684                 *(struct timeval *)data = com->dcd_timestamp;
1685                 break;
1686         default:
1687                 crit_exit();
1688                 lwkt_reltoken(&tty_token);
1689                 return (ENOTTY);
1690         }
1691         crit_exit();
1692         lwkt_reltoken(&tty_token);
1693         return (0);
1694 }
1695
1696 static void
1697 siopoll(void *data, void *frame)
1698 {
1699         int             unit;
1700
1701         lwkt_gettoken(&tty_token);
1702 #ifdef CyDebug
1703         ++cy_timeouts;
1704 #endif
1705         if (com_events == 0) {
1706                 lwkt_reltoken(&tty_token);
1707                 return;
1708         }
1709 repeat:
1710         for (unit = 0; unit < NSIO; ++unit) {
1711                 struct com_s    *com;
1712                 int             incc;
1713                 struct tty      *tp;
1714
1715                 com = com_addr(unit);
1716                 if (com == NULL)
1717                         continue;
1718                 tp = com->tp;
1719                 if (tp == NULL) {
1720                         /*
1721                          * XXX forget any events related to closed devices
1722                          * (actually never opened devices) so that we don't
1723                          * loop.
1724                          */
1725                         disable_intr();
1726                         incc = com->iptr - com->ibuf;
1727                         com->iptr = com->ibuf;
1728                         if (com->state & CS_CHECKMSR) {
1729                                 incc += LOTS_OF_EVENTS;
1730                                 com->state &= ~CS_CHECKMSR;
1731                         }
1732                         com_events -= incc;
1733                         enable_intr();
1734                         if (incc != 0)
1735                                 log(LOG_DEBUG,
1736                                     "sio%d: %d events for device with no tp\n",
1737                                     unit, incc);
1738                         continue;
1739                 }
1740                 if (com->iptr != com->ibuf) {
1741                         disable_intr();
1742                         sioinput(com);
1743                         enable_intr();
1744                 }
1745                 if (com->state & CS_CHECKMSR) {
1746                         u_char  delta_modem_status;
1747
1748                         disable_intr();
1749                         delta_modem_status = com->last_modem_status
1750                                              ^ com->prev_modem_status;
1751                         com->prev_modem_status = com->last_modem_status;
1752                         com_events -= LOTS_OF_EVENTS;
1753                         com->state &= ~CS_CHECKMSR;
1754                         enable_intr();
1755                         if (delta_modem_status & MSR_DCD)
1756                                 (*linesw[tp->t_line].l_modem)
1757                                         (tp, com->prev_modem_status & MSR_DCD);
1758                 }
1759                 if (com->extra_state & CSE_ODONE) {
1760                         disable_intr();
1761                         com_events -= LOTS_OF_EVENTS;
1762                         com->extra_state &= ~CSE_ODONE;
1763                         enable_intr();
1764                         if (!(com->state & CS_BUSY)) {
1765                                 tp->t_state &= ~TS_BUSY;
1766                                 ttwwakeup(com->tp);
1767                         }
1768                         if (com->etc != ETC_NONE) {
1769                                 if (com->etc == ETC_BREAK_ENDED)
1770                                         com->etc = ETC_NONE;
1771                                 wakeup(&com->etc);
1772                         }
1773                 }
1774                 if (com->state & CS_ODONE) {
1775                         disable_intr();
1776                         com_events -= LOTS_OF_EVENTS;
1777                         com->state &= ~CS_ODONE;
1778                         enable_intr();
1779                         (*linesw[tp->t_line].l_start)(tp);
1780                 }
1781                 if (com_events == 0)
1782                         break;
1783         }
1784         if (com_events >= LOTS_OF_EVENTS)
1785                 goto repeat;
1786         lwkt_reltoken(&tty_token);
1787 }
1788
1789 static int
1790 comparam(struct tty *tp, struct termios *t)
1791 {
1792         int             bits;
1793         int             cflag;
1794         struct com_s    *com;
1795         u_char          cor_change;
1796         u_long          cy_clock;
1797         int             idivisor;
1798         int             iflag;
1799         int             iprescaler;
1800         int             itimeout;
1801         int             odivisor;
1802         int             oprescaler;
1803         u_char          opt;
1804         int             unit;
1805
1806         lwkt_gettoken(&tty_token);
1807         /* do historical conversions */
1808         if (t->c_ispeed == 0)
1809                 t->c_ispeed = t->c_ospeed;
1810
1811         unit = DEV_TO_UNIT(tp->t_dev);
1812         com = com_addr(unit);
1813
1814         /* check requested parameters */
1815         cy_clock = CY_CLOCK(com->gfrcr_image);
1816         idivisor = comspeed(t->c_ispeed, cy_clock, &iprescaler);
1817         if (idivisor < 0) {
1818                 lwkt_reltoken(&tty_token);
1819                 return (EINVAL);
1820         }
1821         odivisor = comspeed(t->c_ospeed, cy_clock, &oprescaler);
1822         if (odivisor < 0) {
1823                 lwkt_reltoken(&tty_token);
1824                 return (EINVAL);
1825         }
1826
1827         /* parameters are OK, convert them to the com struct and the device */
1828         crit_enter();
1829         if (odivisor == 0)
1830                 (void)commctl(com, TIOCM_DTR, DMBIC);   /* hang up line */
1831         else
1832                 (void)commctl(com, TIOCM_DTR, DMBIS);
1833
1834         /*
1835          * This returns with interrupts disabled so that we can complete
1836          * the speed change atomically.
1837          */
1838         (void) siosetwater(com, t->c_ispeed);
1839
1840         /* XXX we don't actually change the speed atomically. */
1841         enable_intr();
1842
1843         if (idivisor != 0) {
1844                 cd_setreg(com, CD1400_RBPR, idivisor);
1845                 cd_setreg(com, CD1400_RCOR, iprescaler);
1846         }
1847         if (odivisor != 0) {
1848                 cd_setreg(com, CD1400_TBPR, odivisor);
1849                 cd_setreg(com, CD1400_TCOR, oprescaler);
1850         }
1851
1852         /*
1853          * channel control
1854          *      receiver enable
1855          *      transmitter enable (always set)
1856          */
1857         cflag = t->c_cflag;
1858         opt = CD1400_CCR_CMDCHANCTL | CD1400_CCR_XMTEN
1859               | (cflag & CREAD ? CD1400_CCR_RCVEN : CD1400_CCR_RCVDIS);
1860         if (opt != com->channel_control) {
1861                 com->channel_control = opt;
1862                 cd1400_channel_cmd(com, opt);
1863         }
1864
1865 #ifdef Smarts
1866         /* set special chars */
1867         /* XXX if one is _POSIX_VDISABLE, can't use some others */
1868         if (t->c_cc[VSTOP] != _POSIX_VDISABLE)
1869                 cd_setreg(com, CD1400_SCHR1, t->c_cc[VSTOP]);
1870         if (t->c_cc[VSTART] != _POSIX_VDISABLE)
1871                 cd_setreg(com, CD1400_SCHR2, t->c_cc[VSTART]);
1872         if (t->c_cc[VINTR] != _POSIX_VDISABLE)
1873                 cd_setreg(com, CD1400_SCHR3, t->c_cc[VINTR]);
1874         if (t->c_cc[VSUSP] != _POSIX_VDISABLE)
1875                 cd_setreg(com, CD1400_SCHR4, t->c_cc[VSUSP]);
1876 #endif
1877
1878         /*
1879          * set channel option register 1 -
1880          *      parity mode
1881          *      stop bits
1882          *      char length
1883          */
1884         opt = 0;
1885         /* parity */
1886         if (cflag & PARENB) {
1887                 if (cflag & PARODD)
1888                         opt |= CD1400_COR1_PARODD;
1889                 opt |= CD1400_COR1_PARNORMAL;
1890         }
1891         iflag = t->c_iflag;
1892         if (!(iflag & INPCK))
1893                 opt |= CD1400_COR1_NOINPCK;
1894         bits = 1 + 1;
1895         /* stop bits */
1896         if (cflag & CSTOPB) {
1897                 ++bits;
1898                 opt |= CD1400_COR1_STOP2;
1899         }
1900         /* char length */
1901         switch (cflag & CSIZE) {
1902         case CS5:
1903                 bits += 5;
1904                 opt |= CD1400_COR1_CS5;
1905                 break;
1906         case CS6:
1907                 bits += 6;
1908                 opt |= CD1400_COR1_CS6;
1909                 break;
1910         case CS7:
1911                 bits += 7;
1912                 opt |= CD1400_COR1_CS7;
1913                 break;
1914         default:
1915                 bits += 8;
1916                 opt |= CD1400_COR1_CS8;
1917                 break;
1918         }
1919         cor_change = 0;
1920         if (opt != com->cor[0]) {
1921                 cor_change |= CD1400_CCR_COR1;
1922                 cd_setreg(com, CD1400_COR1, com->cor[0] = opt);
1923         }
1924
1925         /*
1926          * Set receive time-out period, normally to max(one char time, 5 ms).
1927          */
1928         if (t->c_ispeed == 0)
1929                 itimeout = cd_getreg(com, CD1400_RTPR);
1930         else {
1931                 itimeout = (1000 * bits + t->c_ispeed - 1) / t->c_ispeed;
1932 #ifdef SOFT_HOTCHAR
1933 #define MIN_RTP         1
1934 #else
1935 #define MIN_RTP         5
1936 #endif
1937                 if (itimeout < MIN_RTP)
1938                         itimeout = MIN_RTP;
1939         }
1940         if (!(t->c_lflag & ICANON) && t->c_cc[VMIN] != 0 && t->c_cc[VTIME] != 0
1941             && t->c_cc[VTIME] * 10 > itimeout)
1942                 itimeout = t->c_cc[VTIME] * 10;
1943         if (itimeout > 255)
1944                 itimeout = 255;
1945         cd_setreg(com, CD1400_RTPR, itimeout);
1946
1947         /*
1948          * set channel option register 2 -
1949          *      flow control
1950          */
1951         opt = 0;
1952 #ifdef Smarts
1953         if (iflag & IXANY)
1954                 opt |= CD1400_COR2_IXANY;
1955         if (iflag & IXOFF)
1956                 opt |= CD1400_COR2_IXOFF;
1957 #endif
1958 #ifndef SOFT_CTS_OFLOW
1959         if (cflag & CCTS_OFLOW)
1960                 opt |= CD1400_COR2_CCTS_OFLOW;
1961 #endif
1962         disable_intr();
1963         if (opt != com->cor[1]) {
1964                 cor_change |= CD1400_CCR_COR2;
1965                 cd_setreg(com, CD1400_COR2, com->cor[1] = opt);
1966         }
1967         enable_intr();
1968
1969         /*
1970          * set channel option register 3 -
1971          *      receiver FIFO interrupt threshold
1972          *      flow control
1973          */
1974         opt = RxFifoThreshold;
1975 #ifdef Smarts
1976         if (t->c_lflag & ICANON)
1977                 opt |= CD1400_COR3_SCD34;       /* detect INTR & SUSP chars */
1978         if (iflag & IXOFF)
1979                 /* detect and transparently handle START and STOP chars */
1980                 opt |= CD1400_COR3_FCT | CD1400_COR3_SCD12;
1981 #endif
1982         if (opt != com->cor[2]) {
1983                 cor_change |= CD1400_CCR_COR3;
1984                 cd_setreg(com, CD1400_COR3, com->cor[2] = opt);
1985         }
1986
1987         /* notify the CD1400 if COR1-3 have changed */
1988         if (cor_change)
1989                 cd1400_channel_cmd(com, CD1400_CCR_CMDCORCHG | cor_change);
1990
1991         /*
1992          * set channel option register 4 -
1993          *      CR/NL processing
1994          *      break processing
1995          *      received exception processing
1996          */
1997         opt = 0;
1998         if (iflag & IGNCR)
1999                 opt |= CD1400_COR4_IGNCR;
2000 #ifdef Smarts
2001         /*
2002          * we need a new ttyinput() for this, as we don't want to
2003          * have ICRNL && INLCR being done in both layers, or to have
2004          * synchronisation problems
2005          */
2006         if (iflag & ICRNL)
2007                 opt |= CD1400_COR4_ICRNL;
2008         if (iflag & INLCR)
2009                 opt |= CD1400_COR4_INLCR;
2010 #endif
2011         if (iflag & IGNBRK)
2012                 opt |= CD1400_COR4_IGNBRK | CD1400_COR4_NOBRKINT;
2013         /*
2014          * The `-ignbrk -brkint parmrk' case is not handled by the hardware,
2015          * so only tell the hardware about -brkint if -parmrk.
2016          */
2017         if (!(iflag & (BRKINT | PARMRK)))
2018                 opt |= CD1400_COR4_NOBRKINT;
2019 #if 0
2020         /* XXX using this "intelligence" breaks reporting of overruns. */
2021         if (iflag & IGNPAR)
2022                 opt |= CD1400_COR4_PFO_DISCARD;
2023         else {
2024                 if (iflag & PARMRK)
2025                         opt |= CD1400_COR4_PFO_ESC;
2026                 else
2027                         opt |= CD1400_COR4_PFO_NUL;
2028         }
2029 #else
2030         opt |= CD1400_COR4_PFO_EXCEPTION;
2031 #endif
2032         cd_setreg(com, CD1400_COR4, opt);
2033
2034         /*
2035          * set channel option register 5 -
2036          */
2037         opt = 0;
2038         if (iflag & ISTRIP)
2039                 opt |= CD1400_COR5_ISTRIP;
2040         if (t->c_iflag & IEXTEN)
2041                 /* enable LNEXT (e.g. ctrl-v quoting) handling */
2042                 opt |= CD1400_COR5_LNEXT;
2043 #ifdef Smarts
2044         if (t->c_oflag & ONLCR)
2045                 opt |= CD1400_COR5_ONLCR;
2046         if (t->c_oflag & OCRNL)
2047                 opt |= CD1400_COR5_OCRNL;
2048 #endif
2049         cd_setreg(com, CD1400_COR5, opt);
2050
2051         /*
2052          * We always generate modem status change interrupts for CD changes.
2053          * Among other things, this is necessary to track TS_CARR_ON for
2054          * pstat to print even when the driver doesn't care.  CD changes
2055          * should be rare so interrupts for them are not worth extra code to
2056          * avoid.  We avoid interrupts for other modem status changes (except
2057          * for CTS changes when SOFT_CTS_OFLOW is configured) since this is
2058          * simplest and best.
2059          */
2060
2061         /*
2062          * set modem change option register 1
2063          *      generate modem interrupts on which 1 -> 0 input transitions
2064          *      also controls auto-DTR output flow-control, which we don't use
2065          */
2066         opt = CD1400_MCOR1_CDzd;
2067 #ifdef SOFT_CTS_OFLOW
2068         if (cflag & CCTS_OFLOW)
2069                 opt |= CD1400_MCOR1_CTSzd;
2070 #endif
2071         cd_setreg(com, CD1400_MCOR1, opt);
2072
2073         /*
2074          * set modem change option register 2
2075          *      generate modem interrupts on specific 0 -> 1 input transitions
2076          */
2077         opt = CD1400_MCOR2_CDod;
2078 #ifdef SOFT_CTS_OFLOW
2079         if (cflag & CCTS_OFLOW)
2080                 opt |= CD1400_MCOR2_CTSod;
2081 #endif
2082         cd_setreg(com, CD1400_MCOR2, opt);
2083
2084         /*
2085          * XXX should have done this long ago, but there is too much state
2086          * to change all atomically.
2087          */
2088         disable_intr();
2089
2090         com->state &= ~CS_TTGO;
2091         if (!(tp->t_state & TS_TTSTOP))
2092                 com->state |= CS_TTGO;
2093         if (cflag & CRTS_IFLOW) {
2094                 com->state |= CS_RTS_IFLOW;
2095                 /*
2096                  * If CS_RTS_IFLOW just changed from off to on, the change
2097                  * needs to be propagated to MCR_RTS.  This isn't urgent,
2098                  * so do it later by calling comstart() instead of repeating
2099                  * a lot of code from comstart() here.
2100                  */
2101         } else if (com->state & CS_RTS_IFLOW) {
2102                 com->state &= ~CS_RTS_IFLOW;
2103                 /*
2104                  * CS_RTS_IFLOW just changed from on to off.  Force MCR_RTS
2105                  * on here, since comstart() won't do it later.
2106                  */
2107 #if 0
2108                 outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
2109 #else
2110                 cd_setreg(com, com->mcr_rts_reg,
2111                           com->mcr_image |= com->mcr_rts);
2112 #endif
2113         }
2114
2115         /*
2116          * Set up state to handle output flow control.
2117          * XXX - worth handling MDMBUF (DCD) flow control at the lowest level?
2118          * Now has 10+ msec latency, while CTS flow has 50- usec latency.
2119          */
2120         com->state |= CS_ODEVREADY;
2121 #ifdef SOFT_CTS_OFLOW
2122         com->state &= ~CS_CTS_OFLOW;
2123         if (cflag & CCTS_OFLOW) {
2124                 com->state |= CS_CTS_OFLOW;
2125                 if (!(com->last_modem_status & MSR_CTS))
2126                         com->state &= ~CS_ODEVREADY;
2127         }
2128 #endif
2129         /* XXX shouldn't call functions while intrs are disabled. */
2130         disc_optim(tp, t, com);
2131 #if 0
2132         /*
2133          * Recover from fiddling with CS_TTGO.  We used to call siointr1()
2134          * unconditionally, but that defeated the careful discarding of
2135          * stale input in sioopen().
2136          */
2137         if (com->state >= (CS_BUSY | CS_TTGO))
2138                 siointr1(com);
2139 #endif
2140         if (com->state >= (CS_BUSY | CS_TTGO | CS_ODEVREADY)) {
2141                 if (!(com->intr_enable & CD1400_SRER_TXRDY))
2142                         cd_setreg(com, CD1400_SRER,
2143                                   com->intr_enable
2144                                   = (com->intr_enable & ~CD1400_SRER_TXMPTY)
2145                                     | CD1400_SRER_TXRDY);
2146         } else {
2147                 if (com->intr_enable & CD1400_SRER_TXRDY)
2148                         cd_setreg(com, CD1400_SRER,
2149                                   com->intr_enable
2150                                   = (com->intr_enable & ~CD1400_SRER_TXRDY)
2151                                     | CD1400_SRER_TXMPTY);
2152         }
2153
2154         enable_intr();
2155         crit_exit();
2156         comstart(tp);
2157         if (com->ibufold != NULL) {
2158                 kfree(com->ibufold, M_DEVBUF);
2159                 com->ibufold = NULL;
2160         }
2161         lwkt_reltoken(&tty_token);
2162         return (0);
2163 }
2164
2165 /*
2166  * NOTE: Must be called with tty_token held
2167  */
2168 static int
2169 siosetwater(struct com_s *com, speed_t speed)
2170 {
2171         int             cp4ticks;
2172         u_char          *ibuf;
2173         int             ibufsize;
2174         struct tty      *tp;
2175
2176         ASSERT_LWKT_TOKEN_HELD(&tty_token);
2177
2178         /*
2179          * Make the buffer size large enough to handle a softtty interrupt
2180          * latency of about 2 ticks without loss of throughput or data
2181          * (about 3 ticks if input flow control is not used or not honoured,
2182          * but a bit less for CS5-CS7 modes).
2183          */
2184         cp4ticks = speed / 10 / hz * 4;
2185         for (ibufsize = 128; ibufsize < cp4ticks;)
2186                 ibufsize <<= 1;
2187         if (ibufsize == com->ibufsize) {
2188                 disable_intr();
2189                 return (0);
2190         }
2191
2192         /*
2193          * Allocate input buffer.  The extra factor of 2 in the size is
2194          * to allow for an error byte for each input byte.
2195          */
2196         ibuf = kmalloc(2 * ibufsize, M_DEVBUF, M_WAITOK);
2197
2198         /* Initialize non-critical variables. */
2199         com->ibufold = com->ibuf;
2200         com->ibufsize = ibufsize;
2201         tp = com->tp;
2202         if (tp != NULL) {
2203                 tp->t_ififosize = 2 * ibufsize;
2204                 tp->t_ispeedwat = (speed_t)-1;
2205                 tp->t_ospeedwat = (speed_t)-1;
2206         }
2207
2208         /*
2209          * Read current input buffer, if any.  Continue with interrupts
2210          * disabled.
2211          */
2212         disable_intr();
2213         if (com->iptr != com->ibuf)
2214                 sioinput(com);
2215
2216         /*-
2217          * Initialize critical variables, including input buffer watermarks.
2218          * The external device is asked to stop sending when the buffer
2219          * exactly reaches high water, or when the high level requests it.
2220          * The high level is notified immediately (rather than at a later
2221          * clock tick) when this watermark is reached.
2222          * The buffer size is chosen so the watermark should almost never
2223          * be reached.
2224          * The low watermark is invisibly 0 since the buffer is always
2225          * emptied all at once.
2226          */
2227         com->iptr = com->ibuf = ibuf;
2228         com->ibufend = ibuf + ibufsize;
2229         com->ierroff = ibufsize;
2230         com->ihighwater = ibuf + 3 * ibufsize / 4;
2231         return (0);
2232 }
2233
2234 static void
2235 comstart(struct tty *tp)
2236 {
2237         struct com_s    *com;
2238 #ifdef CyDebug
2239         bool_t          started;
2240 #endif
2241         int             unit;
2242
2243         unit = DEV_TO_UNIT(tp->t_dev);
2244         com = com_addr(unit);
2245         crit_enter();
2246         lwkt_gettoken(&tty_token);
2247
2248 #ifdef CyDebug
2249         ++com->start_count;
2250         started = FALSE;
2251 #endif
2252
2253         disable_intr();
2254         if (tp->t_state & TS_TTSTOP) {
2255                 com->state &= ~CS_TTGO;
2256                 if (com->intr_enable & CD1400_SRER_TXRDY)
2257                         cd_setreg(com, CD1400_SRER,
2258                                   com->intr_enable
2259                                   = (com->intr_enable & ~CD1400_SRER_TXRDY)
2260                                     | CD1400_SRER_TXMPTY);
2261         } else {
2262                 com->state |= CS_TTGO;
2263                 if (com->state >= (CS_BUSY | CS_TTGO | CS_ODEVREADY)
2264                     && !(com->intr_enable & CD1400_SRER_TXRDY))
2265                         cd_setreg(com, CD1400_SRER,
2266                                   com->intr_enable
2267                                   = (com->intr_enable & ~CD1400_SRER_TXMPTY)
2268                                     | CD1400_SRER_TXRDY);
2269         }
2270         if (tp->t_state & TS_TBLOCK) {
2271                 if (com->mcr_image & com->mcr_rts && com->state & CS_RTS_IFLOW)
2272 #if 0
2273                         outb(com->modem_ctl_port, com->mcr_image &= ~MCR_RTS);
2274 #else
2275                         cd_setreg(com, com->mcr_rts_reg,
2276                                   com->mcr_image &= ~com->mcr_rts);
2277 #endif
2278         } else {
2279                 if (!(com->mcr_image & com->mcr_rts)
2280                     && com->iptr < com->ihighwater
2281                     && com->state & CS_RTS_IFLOW)
2282 #if 0
2283                         outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
2284 #else
2285                         cd_setreg(com, com->mcr_rts_reg,
2286                                   com->mcr_image |= com->mcr_rts);
2287 #endif
2288         }
2289         enable_intr();
2290         if (tp->t_state & (TS_TIMEOUT | TS_TTSTOP)) {
2291                 ttwwakeup(tp);
2292                 lwkt_reltoken(&tty_token);
2293                 crit_exit();
2294                 return;
2295         }
2296         if (tp->t_outq.c_cc != 0) {
2297                 struct lbq      *qp;
2298                 struct lbq      *next;
2299
2300                 if (!com->obufs[0].l_queued) {
2301 #ifdef CyDebug
2302                         started = TRUE;
2303 #endif
2304                         com->obufs[0].l_tail
2305                             = com->obuf1 + q_to_b(&tp->t_outq, com->obuf1,
2306                                                   sizeof com->obuf1);
2307                         com->obufs[0].l_next = NULL;
2308                         com->obufs[0].l_queued = TRUE;
2309                         disable_intr();
2310                         if (com->state & CS_BUSY) {
2311                                 qp = com->obufq.l_next;
2312                                 while ((next = qp->l_next) != NULL)
2313                                         qp = next;
2314                                 qp->l_next = &com->obufs[0];
2315                         } else {
2316                                 com->obufq.l_head = com->obufs[0].l_head;
2317                                 com->obufq.l_tail = com->obufs[0].l_tail;
2318                                 com->obufq.l_next = &com->obufs[0];
2319                                 com->state |= CS_BUSY;
2320                                 if (com->state >= (CS_BUSY | CS_TTGO
2321                                                    | CS_ODEVREADY))
2322                                         cd_setreg(com, CD1400_SRER,
2323                                                   com->intr_enable
2324                                                   = (com->intr_enable
2325                                                     & ~CD1400_SRER_TXMPTY)
2326                                                     | CD1400_SRER_TXRDY);
2327                         }
2328                         enable_intr();
2329                 }
2330                 if (tp->t_outq.c_cc != 0 && !com->obufs[1].l_queued) {
2331 #ifdef CyDebug
2332                         started = TRUE;
2333 #endif
2334                         com->obufs[1].l_tail
2335                             = com->obuf2 + q_to_b(&tp->t_outq, com->obuf2,
2336                                                   sizeof com->obuf2);
2337                         com->obufs[1].l_next = NULL;
2338                         com->obufs[1].l_queued = TRUE;
2339                         disable_intr();
2340                         if (com->state & CS_BUSY) {
2341                                 qp = com->obufq.l_next;
2342                                 while ((next = qp->l_next) != NULL)
2343                                         qp = next;
2344                                 qp->l_next = &com->obufs[1];
2345                         } else {
2346                                 com->obufq.l_head = com->obufs[1].l_head;
2347                                 com->obufq.l_tail = com->obufs[1].l_tail;
2348                                 com->obufq.l_next = &com->obufs[1];
2349                                 com->state |= CS_BUSY;
2350                                 if (com->state >= (CS_BUSY | CS_TTGO
2351                                                    | CS_ODEVREADY))
2352                                         cd_setreg(com, CD1400_SRER,
2353                                                   com->intr_enable
2354                                                   = (com->intr_enable
2355                                                     & ~CD1400_SRER_TXMPTY)
2356                                                     | CD1400_SRER_TXRDY);
2357                         }
2358                         enable_intr();
2359                 }
2360                 tp->t_state |= TS_BUSY;
2361         }
2362 #ifdef CyDebug
2363         if (started)
2364                 ++com->start_real;
2365 #endif
2366 #if 0
2367         disable_intr();
2368         if (com->state >= (CS_BUSY | CS_TTGO))
2369                 siointr1(com);  /* fake interrupt to start output */
2370         enable_intr();
2371 #endif
2372         ttwwakeup(tp);
2373         lwkt_reltoken(&tty_token);
2374         crit_exit();
2375 }
2376
2377 static void
2378 comstop(struct tty *tp, int rw)
2379 {
2380         struct com_s    *com;
2381         bool_t          wakeup_etc;
2382
2383         lwkt_gettoken(&tty_token);
2384         com = com_addr(DEV_TO_UNIT(tp->t_dev));
2385         wakeup_etc = FALSE;
2386         disable_intr();
2387         if (rw & FWRITE) {
2388                 com->obufs[0].l_queued = FALSE;
2389                 com->obufs[1].l_queued = FALSE;
2390                 if (com->extra_state & CSE_ODONE) {
2391                         com_events -= LOTS_OF_EVENTS;
2392                         com->extra_state &= ~CSE_ODONE;
2393                         if (com->etc != ETC_NONE) {
2394                                 if (com->etc == ETC_BREAK_ENDED)
2395                                         com->etc = ETC_NONE;
2396                                 wakeup_etc = TRUE;
2397                         }
2398                 }
2399                 com->tp->t_state &= ~TS_BUSY;
2400                 if (com->state & CS_ODONE)
2401                         com_events -= LOTS_OF_EVENTS;
2402                 com->state &= ~(CS_ODONE | CS_BUSY);
2403         }
2404         if (rw & FREAD) {
2405                 /* XXX no way to reset only input fifo. */
2406                 com_events -= (com->iptr - com->ibuf);
2407                 com->iptr = com->ibuf;
2408         }
2409         enable_intr();
2410         if (wakeup_etc)
2411                 wakeup(&com->etc);
2412         if (rw & FWRITE && com->etc == ETC_NONE)
2413                 cd1400_channel_cmd(com, CD1400_CCR_CMDRESET | CD1400_CCR_FTF);
2414         comstart(tp);
2415         lwkt_reltoken(&tty_token);
2416 }
2417
2418 /*
2419  * NOTE: Must be called with tty_token held
2420  */
2421 static int
2422 commctl(struct com_s *com, int bits, int how)
2423 {
2424         int     mcr;
2425         int     msr;
2426
2427         ASSERT_LWKT_TOKEN_HELD(&tty_token);
2428
2429         if (how == DMGET) {
2430                 if (com->channel_control & CD1400_CCR_RCVEN)
2431                         bits |= TIOCM_LE;
2432                 mcr = com->mcr_image;
2433                 if (mcr & com->mcr_dtr)
2434                         bits |= TIOCM_DTR;
2435                 if (mcr & com->mcr_rts)
2436                         /* XXX wired on for Cyclom-8Ys */
2437                         bits |= TIOCM_RTS;
2438
2439                 /*
2440                  * We must read the modem status from the hardware because
2441                  * we don't generate modem status change interrupts for all
2442                  * changes, so com->prev_modem_status is not guaranteed to
2443                  * be up to date.  This is safe, unlike for sio, because
2444                  * reading the status register doesn't clear pending modem
2445                  * status change interrupts.
2446                  */
2447                 msr = cd_getreg(com, CD1400_MSVR2);
2448
2449                 if (msr & MSR_CTS)
2450                         bits |= TIOCM_CTS;
2451                 if (msr & MSR_DCD)
2452                         bits |= TIOCM_CD;
2453                 if (msr & MSR_DSR)
2454                         bits |= TIOCM_DSR;
2455                 if (msr & MSR_RI)
2456                         /* XXX not connected except for Cyclom-16Y? */
2457                         bits |= TIOCM_RI;
2458                 return (bits);
2459         }
2460         mcr = 0;
2461         if (bits & TIOCM_DTR)
2462                 mcr |= com->mcr_dtr;
2463         if (bits & TIOCM_RTS)
2464                 mcr |= com->mcr_rts;
2465         disable_intr();
2466         switch (how) {
2467         case DMSET:
2468                 com->mcr_image = mcr;
2469                 cd_setreg(com, CD1400_MSVR1, mcr);
2470                 cd_setreg(com, CD1400_MSVR2, mcr);
2471                 break;
2472         case DMBIS:
2473                 com->mcr_image = mcr = com->mcr_image | mcr;
2474                 cd_setreg(com, CD1400_MSVR1, mcr);
2475                 cd_setreg(com, CD1400_MSVR2, mcr);
2476                 break;
2477         case DMBIC:
2478                 com->mcr_image = mcr = com->mcr_image & ~mcr;
2479                 cd_setreg(com, CD1400_MSVR1, mcr);
2480                 cd_setreg(com, CD1400_MSVR2, mcr);
2481                 break;
2482         }
2483         enable_intr();
2484         return (0);
2485 }
2486
2487 /*
2488  * NOTE: Must be called with tty_token held
2489  */
2490 static void
2491 siosettimeout(void)
2492 {
2493         struct com_s    *com;
2494         bool_t          someopen;
2495         int             unit;
2496
2497         ASSERT_LWKT_TOKEN_HELD(&tty_token);
2498         /*
2499          * Set our timeout period to 1 second if no polled devices are open.
2500          * Otherwise set it to max(1/200, 1/hz).
2501          * Enable timeouts iff some device is open.
2502          */
2503         callout_stop(&sio_timeout_handle);
2504         sio_timeout = hz;
2505         someopen = FALSE;
2506         for (unit = 0; unit < NSIO; ++unit) {
2507                 com = com_addr(unit);
2508                 if (com != NULL && com->tp != NULL
2509                     && com->tp->t_state & TS_ISOPEN) {
2510                         someopen = TRUE;
2511 #if 0
2512                         if (com->poll || com->poll_output) {
2513                                 sio_timeout = hz > 200 ? hz / 200 : 1;
2514                                 break;
2515                         }
2516 #endif
2517                 }
2518         }
2519         if (someopen) {
2520                 sio_timeouts_until_log = hz / sio_timeout;
2521                 callout_reset(&sio_timeout_handle, sio_timeout,
2522                                 comwakeup, NULL);
2523         } else {
2524                 /* Flush error messages, if any. */
2525                 sio_timeouts_until_log = 1;
2526                 comwakeup(NULL);
2527                 callout_stop(&sio_timeout_handle);
2528         }
2529 }
2530
2531 static void
2532 comwakeup(void *chan)
2533 {
2534         struct com_s    *com;
2535         int             unit;
2536
2537         lwkt_gettoken(&tty_token);
2538         callout_reset(&sio_timeout_handle, sio_timeout, comwakeup, NULL);
2539
2540 #if 0
2541         /*
2542          * Recover from lost output interrupts.
2543          * Poll any lines that don't use interrupts.
2544          */
2545         for (unit = 0; unit < NSIO; ++unit) {
2546                 com = com_addr(unit);
2547                 if (com != NULL
2548                     && (com->state >= (CS_BUSY | CS_TTGO) || com->poll)) {
2549                         disable_intr();
2550                         siointr1(com);
2551                         enable_intr();
2552                 }
2553         }
2554 #endif
2555
2556         /*
2557          * Check for and log errors, but not too often.
2558          */
2559         if (--sio_timeouts_until_log > 0) {
2560                 lwkt_reltoken(&tty_token);
2561                 return;
2562         }
2563         sio_timeouts_until_log = hz / sio_timeout;
2564         for (unit = 0; unit < NSIO; ++unit) {
2565                 int     errnum;
2566
2567                 com = com_addr(unit);
2568                 if (com == NULL)
2569                         continue;
2570                 for (errnum = 0; errnum < CE_NTYPES; ++errnum) {
2571                         u_int   delta;
2572                         u_long  total;
2573
2574                         disable_intr();
2575                         delta = com->delta_error_counts[errnum];
2576                         com->delta_error_counts[errnum] = 0;
2577                         enable_intr();
2578                         if (delta == 0)
2579                                 continue;
2580                         total = com->error_counts[errnum] += delta;
2581                         log(LOG_ERR, "cy%d: %u more %s%s (total %lu)\n",
2582                             unit, delta, error_desc[errnum],
2583                             delta == 1 ? "" : "s", total);
2584                 }
2585         }
2586         lwkt_reltoken(&tty_token);
2587 }
2588
2589 static void
2590 disc_optim(struct tty *tp, struct termios *t, struct com_s *com)
2591 {
2592 #ifndef SOFT_HOTCHAR
2593         u_char  opt;
2594 #endif
2595
2596         lwkt_gettoken(&tty_token);
2597         /*
2598          * XXX can skip a lot more cases if Smarts.  Maybe
2599          * (IGNCR | ISTRIP | IXON) in c_iflag.  But perhaps we
2600          * shouldn't skip if (TS_CNTTB | TS_LNCH) is set in t_state.
2601          */
2602         if (!(t->c_iflag & (ICRNL | IGNCR | IMAXBEL | INLCR | ISTRIP | IXON))
2603             && (!(t->c_iflag & BRKINT) || (t->c_iflag & IGNBRK))
2604             && (!(t->c_iflag & PARMRK)
2605                 || (t->c_iflag & (IGNPAR | IGNBRK)) == (IGNPAR | IGNBRK))
2606             && !(t->c_lflag & (ECHO | ICANON | IEXTEN | ISIG | PENDIN))
2607             && linesw[tp->t_line].l_rint == ttyinput)
2608                 tp->t_state |= TS_CAN_BYPASS_L_RINT;
2609         else
2610                 tp->t_state &= ~TS_CAN_BYPASS_L_RINT;
2611         com->hotchar = linesw[tp->t_line].l_hotchar;
2612 #ifndef SOFT_HOTCHAR
2613         opt = com->cor[2] & ~CD1400_COR3_SCD34;
2614         if (com->hotchar != 0) {
2615                 cd_setreg(com, CD1400_SCHR3, com->hotchar);
2616                 cd_setreg(com, CD1400_SCHR4, com->hotchar);
2617                 opt |= CD1400_COR3_SCD34;
2618         }
2619         if (opt != com->cor[2]) {
2620                 cd_setreg(com, CD1400_COR3, com->cor[2] = opt);
2621                 cd1400_channel_cmd(com, CD1400_CCR_CMDCORCHG | CD1400_CCR_COR3);
2622         }
2623 #endif
2624         lwkt_reltoken(&tty_token);
2625 }
2626
2627 #ifdef Smarts
2628 /* standard line discipline input routine */
2629 int
2630 cyinput(int c, struct tty *tp)
2631 {
2632         /* XXX duplicate ttyinput(), but without the IXOFF/IXON/ISTRIP/IPARMRK
2633          * bits, as they are done by the CD1400.  Hardly worth the effort,
2634          * given that high-throughput sessions are raw anyhow.
2635          */
2636 }
2637 #endif /* Smarts */
2638
2639 static int
2640 comspeed(speed_t speed, u_long cy_clock, int *prescaler_io)
2641 {
2642         int     actual;
2643         int     error;
2644         int     divider;
2645         int     prescaler;
2646         int     prescaler_unit;
2647
2648         if (speed == 0)
2649                 return (0);
2650         if (speed < 0 || speed > 150000)
2651                 return (-1);
2652
2653         /* determine which prescaler to use */
2654         for (prescaler_unit = 4, prescaler = 2048; prescaler_unit;
2655                 prescaler_unit--, prescaler >>= 2) {
2656                 if (cy_clock / prescaler / speed > 63)
2657                         break;
2658         }
2659
2660         divider = (cy_clock / prescaler * 2 / speed + 1) / 2; /* round off */
2661         if (divider > 255)
2662                 divider = 255;
2663         actual = cy_clock/prescaler/divider;
2664
2665         /* 10 times error in percent: */
2666         error = ((actual - (long)speed) * 2000 / (long)speed + 1) / 2;
2667
2668         /* 3.0% max error tolerance */
2669         if (error < -30 || error > 30)
2670                 return (-1);
2671
2672 #if 0
2673         kprintf("prescaler = %d (%d)\n", prescaler, prescaler_unit);
2674         kprintf("divider = %d (%x)\n", divider, divider);
2675         kprintf("actual = %d\n", actual);
2676         kprintf("error = %d\n", error);
2677 #endif
2678
2679         *prescaler_io = prescaler_unit;
2680         return (divider);
2681 }
2682
2683 /*
2684  * NOTE: Must be called with tty_token held
2685  */
2686 static void
2687 cd1400_channel_cmd(struct com_s *com, int cmd)
2688 {
2689         ASSERT_LWKT_TOKEN_HELD(&tty_token);
2690         cd1400_channel_cmd_wait(com);
2691         cd_setreg(com, CD1400_CCR, cmd);
2692         cd1400_channel_cmd_wait(com);
2693 }
2694
2695 /*
2696  * NOTE: Must be called with tty_token held
2697  */
2698 static void
2699 cd1400_channel_cmd_wait(struct com_s *com)
2700 {
2701         struct timeval  start;
2702         struct timeval  tv;
2703         long            usec;
2704
2705         ASSERT_LWKT_TOKEN_HELD(&tty_token);
2706
2707         if (cd_getreg(com, CD1400_CCR) == 0)
2708                 return;
2709         microtime(&start);
2710         for (;;) {
2711                 if (cd_getreg(com, CD1400_CCR) == 0)
2712                         return;
2713                 microtime(&tv);
2714                 usec = 1000000 * (tv.tv_sec - start.tv_sec) +
2715                     tv.tv_usec - start.tv_usec;
2716                 if (usec >= 5000) {
2717                         log(LOG_ERR,
2718                             "cy%d: channel command timeout (%ld usec)\n",
2719                             com->unit, usec);
2720                         return;
2721                 }
2722         }
2723 }
2724
2725 /*
2726  * NOTE: Must be called with tty_token held
2727  */
2728 static void
2729 cd_etc(struct com_s *com, int etc)
2730 {
2731         ASSERT_LWKT_TOKEN_HELD(&tty_token);
2732         /*
2733          * We can't change the hardware's ETC state while there are any
2734          * characters in the tx fifo, since those characters would be
2735          * interpreted as commands!  Unputting characters from the fifo
2736          * is difficult, so we wait up to 12 character times for the fifo
2737          * to drain.  The command will be delayed for up to 2 character
2738          * times for the tx to become empty.  Unputting characters from
2739          * the tx holding and shift registers is impossible, so we wait
2740          * for the tx to become empty so that the command is sure to be
2741          * executed soon after we issue it.
2742          */
2743         disable_intr();
2744         if (com->etc == etc) {
2745                 enable_intr();
2746                 goto wait;
2747         }
2748         if ((etc == CD1400_ETC_SENDBREAK
2749             && (com->etc == ETC_BREAK_STARTING
2750                 || com->etc == ETC_BREAK_STARTED))
2751             || (etc == CD1400_ETC_STOPBREAK
2752                && (com->etc == ETC_BREAK_ENDING || com->etc == ETC_BREAK_ENDED
2753                    || com->etc == ETC_NONE))) {
2754                 enable_intr();
2755                 return;
2756         }
2757         com->etc = etc;
2758         cd_setreg(com, CD1400_SRER,
2759                   com->intr_enable
2760                   = (com->intr_enable & ~CD1400_SRER_TXRDY) | CD1400_SRER_TXMPTY);
2761         enable_intr();
2762 wait:
2763         while (com->etc == etc
2764                && tsleep(&com->etc, PCATCH, "cyetc", 0) == 0)
2765                 continue;
2766 }
2767
2768 /*
2769  * NOTE: Must be called with tty_token held
2770  */
2771 static int
2772 cd_getreg(struct com_s *com, int reg)
2773 {
2774         struct com_s    *basecom;
2775         u_char  car;
2776         int     cy_align;
2777         u_long  ef;
2778         cy_addr iobase;
2779         int     val;
2780
2781         ASSERT_LWKT_TOKEN_HELD(&tty_token);
2782
2783         basecom = com_addr(com->unit & ~(CD1400_NO_OF_CHANNELS - 1));
2784         car = com->unit & CD1400_CAR_CHAN;
2785         cy_align = com->cy_align;
2786         iobase = com->iobase;
2787         ef = read_eflags();
2788         if (ef & PSL_I)
2789                 disable_intr();
2790         if (basecom->car != car)
2791                 cd_outb(iobase, CD1400_CAR, cy_align, basecom->car = car);
2792         val = cd_inb(iobase, reg, cy_align);
2793         if (ef & PSL_I)
2794                 enable_intr();
2795         return (val);
2796 }
2797
2798 /*
2799  * NOTE: Must be called with tty_token held
2800  */
2801 static void
2802 cd_setreg(struct com_s *com, int reg, int val)
2803 {
2804         struct com_s    *basecom;
2805         u_char  car;
2806         int     cy_align;
2807         u_long  ef;
2808         cy_addr iobase;
2809
2810         ASSERT_LWKT_TOKEN_HELD(&tty_token);
2811
2812         basecom = com_addr(com->unit & ~(CD1400_NO_OF_CHANNELS - 1));
2813         car = com->unit & CD1400_CAR_CHAN;
2814         cy_align = com->cy_align;
2815         iobase = com->iobase;
2816         ef = read_eflags();
2817         if (ef & PSL_I)
2818                 disable_intr();
2819         if (basecom->car != car)
2820                 cd_outb(iobase, CD1400_CAR, cy_align, basecom->car = car);
2821         cd_outb(iobase, reg, cy_align, val);
2822         if (ef & PSL_I)
2823                 enable_intr();
2824 }
2825
2826 #ifdef CyDebug
2827 /* useful in ddb */
2828 void
2829 cystatus(int unit)
2830 {
2831         struct com_s    *com;
2832         cy_addr         iobase;
2833         u_int           ocount;
2834         struct tty      *tp;
2835
2836         com = com_addr(unit);
2837         kprintf("info for channel %d\n", unit);
2838         kprintf("------------------\n");
2839         kprintf("total cyclom service probes:\t%d\n", cy_svrr_probes);
2840         kprintf("calls to upper layer:\t\t%d\n", cy_timeouts);
2841         if (com == NULL)
2842                 return;
2843         lwkt_gettoken(&tty_token);
2844         iobase = com->iobase;
2845         kprintf("\n");
2846         kprintf("cd1400 base address:\\tt%p\n", iobase);
2847         kprintf("saved channel_control:\t\t0x%02x\n", com->channel_control);
2848         kprintf("saved cor1-3:\t\t\t0x%02x 0x%02x 0x%02x\n",
2849                com->cor[0], com->cor[1], com->cor[2]);
2850         kprintf("service request enable reg:\t0x%02x (0x%02x cached)\n",
2851                cd_getreg(com, CD1400_SRER), com->intr_enable);
2852         kprintf("service request register:\t0x%02x\n",
2853                cd_inb(iobase, CD1400_SVRR, com->cy_align));
2854         kprintf("modem status:\t\t\t0x%02x (0x%02x cached)\n",
2855                cd_getreg(com, CD1400_MSVR2), com->prev_modem_status);
2856         kprintf("rx/tx/mdm interrupt registers:\t0x%02x 0x%02x 0x%02x\n",
2857                cd_inb(iobase, CD1400_RIR, com->cy_align),
2858                cd_inb(iobase, CD1400_TIR, com->cy_align),
2859                cd_inb(iobase, CD1400_MIR, com->cy_align));
2860         kprintf("\n");
2861         kprintf("com state:\t\t\t0x%02x\n", com->state);
2862         kprintf("calls to comstart():\t\t%d (%d useful)\n",
2863                com->start_count, com->start_real);
2864         kprintf("rx buffer chars free:\t\t%d\n", com->iptr - com->ibuf);
2865         ocount = 0;
2866         if (com->obufs[0].l_queued)
2867                 ocount += com->obufs[0].l_tail - com->obufs[0].l_head;
2868         if (com->obufs[1].l_queued)
2869                 ocount += com->obufs[1].l_tail - com->obufs[1].l_head;
2870         kprintf("tx buffer chars:\t\t%u\n", ocount);
2871         kprintf("received chars:\t\t\t%d\n", com->bytes_in);
2872         kprintf("received exceptions:\t\t%d\n", com->recv_exception);
2873         kprintf("modem signal deltas:\t\t%d\n", com->mdm);
2874         kprintf("transmitted chars:\t\t%d\n", com->bytes_out);
2875         kprintf("\n");
2876         tp = com->tp;
2877         if (tp != NULL) {
2878                 kprintf("tty state:\t\t\t0x%08x\n", tp->t_state);
2879                 kprintf(
2880                 "upper layer queue lengths:\t%d raw, %d canon, %d output\n",
2881                        tp->t_rawq.c_cc, tp->t_canq.c_cc, tp->t_outq.c_cc);
2882         } else {
2883                 kprintf("tty state:\t\t\tclosed\n");
2884         }
2885         lwkt_reltoken(&tty_token);
2886 }
2887 #endif /* CyDebug */