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