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