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