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