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