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