xref: /netbsd-src/sys/dev/ic/com.c (revision aef5eb5f59cdfe8314f1b5f78ac04eb144e44010)
1 /* $NetBSD: com.c,v 1.378 2022/10/03 20:15:50 riastradh Exp $ */
2 
3 /*-
4  * Copyright (c) 1998, 1999, 2004, 2008 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Charles M. Hannum.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 /*
33  * Copyright (c) 1991 The Regents of the University of California.
34  * All rights reserved.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions
38  * are met:
39  * 1. Redistributions of source code must retain the above copyright
40  *    notice, this list of conditions and the following disclaimer.
41  * 2. Redistributions in binary form must reproduce the above copyright
42  *    notice, this list of conditions and the following disclaimer in the
43  *    documentation and/or other materials provided with the distribution.
44  * 3. Neither the name of the University nor the names of its contributors
45  *    may be used to endorse or promote products derived from this software
46  *    without specific prior written permission.
47  *
48  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58  * SUCH DAMAGE.
59  *
60  *	@(#)com.c	7.5 (Berkeley) 5/16/91
61  */
62 
63 /*
64  * COM driver, uses National Semiconductor NS16450/NS16550AF UART
65  * Supports automatic hardware flow control on StarTech ST16C650A UART
66  *
67  * Lock order:
68  *	tty_lock (IPL_VM)
69  *	-> sc->sc_lock (IPL_HIGH)
70  */
71 
72 #include <sys/cdefs.h>
73 __KERNEL_RCSID(0, "$NetBSD: com.c,v 1.378 2022/10/03 20:15:50 riastradh Exp $");
74 
75 #include "opt_com.h"
76 #include "opt_ddb.h"
77 #include "opt_kgdb.h"
78 #include "opt_lockdebug.h"
79 #include "opt_multiprocessor.h"
80 #include "opt_ntp.h"
81 
82 /* The COM16650 option was renamed to COM_16650. */
83 #ifdef COM16650
84 #error Obsolete COM16650 option; use COM_16650 instead.
85 #endif
86 
87 /*
88  * Override cnmagic(9) macro before including <sys/systm.h>.
89  * We need to know if cn_check_magic triggered debugger, so set a flag.
90  * Callers of cn_check_magic must declare int cn_trapped = 0;
91  * XXX: this is *ugly*!
92  */
93 #define cn_trap()				\
94 	do {					\
95 		console_debugger();		\
96 		cn_trapped = 1;			\
97 		(void)cn_trapped;		\
98 	} while (/* CONSTCOND */ 0)
99 
100 #include <sys/param.h>
101 #include <sys/systm.h>
102 #include <sys/ioctl.h>
103 #include <sys/select.h>
104 #include <sys/poll.h>
105 #include <sys/tty.h>
106 #include <sys/proc.h>
107 #include <sys/conf.h>
108 #include <sys/file.h>
109 #include <sys/uio.h>
110 #include <sys/kernel.h>
111 #include <sys/syslog.h>
112 #include <sys/device.h>
113 #include <sys/malloc.h>
114 #include <sys/timepps.h>
115 #include <sys/vnode.h>
116 #include <sys/kauth.h>
117 #include <sys/intr.h>
118 #ifdef RND_COM
119 #include <sys/rndsource.h>
120 #endif
121 
122 
123 #include <sys/bus.h>
124 
125 #include <dev/ic/comreg.h>
126 #include <dev/ic/comvar.h>
127 #include <dev/ic/ns16550reg.h>
128 #include <dev/ic/st16650reg.h>
129 #include <dev/ic/hayespreg.h>
130 #define	com_lcr	com_cfcr
131 #include <dev/cons.h>
132 
133 #include "ioconf.h"
134 
135 #define	CSR_READ_1(r, o)	\
136 	(r)->cr_read((r), (r)->cr_map[o])
137 #define	CSR_WRITE_1(r, o, v)	\
138 	(r)->cr_write((r), (r)->cr_map[o], (v))
139 #define	CSR_WRITE_MULTI(r, o, p, n)	\
140 	(r)->cr_write_multi((r), (r)->cr_map[o], (p), (n))
141 
142 /*
143  * XXX COM_TYPE_AU1x00 specific
144  */
145 #define	CSR_WRITE_2(r, o, v)	\
146 	bus_space_write_2((r)->cr_iot, (r)->cr_ioh, (r)->cr_map[o], v)
147 #define	CSR_READ_2(r, o)	\
148 	bus_space_read_2((r)->cr_iot, (r)->cr_ioh, (r)->cr_map[o])
149 
150 static void com_enable_debugport(struct com_softc *);
151 
152 void	com_config(struct com_softc *);
153 void	com_shutdown(struct com_softc *);
154 int	comspeed(long, long, int);
155 static	u_char	cflag2lcr(tcflag_t);
156 int	comparam(struct tty *, struct termios *);
157 void	comstart(struct tty *);
158 int	comhwiflow(struct tty *, int);
159 
160 void	com_loadchannelregs(struct com_softc *);
161 void	com_hwiflow(struct com_softc *);
162 void	com_break(struct com_softc *, int);
163 void	com_modem(struct com_softc *, int);
164 void	tiocm_to_com(struct com_softc *, u_long, int);
165 int	com_to_tiocm(struct com_softc *);
166 void	com_iflush(struct com_softc *);
167 
168 int	com_common_getc(dev_t, struct com_regs *);
169 static void	com_common_putc(dev_t, struct com_regs *, int, int);
170 
171 int	cominit(struct com_regs *, int, int, int, tcflag_t);
172 
173 static int comcnreattach(void);
174 
175 int	comcngetc(dev_t);
176 void	comcnputc(dev_t, int);
177 void	comcnpollc(dev_t, int);
178 
179 void	comsoft(void *);
180 static inline void com_rxsoft(struct com_softc *, struct tty *);
181 static inline void com_txsoft(struct com_softc *, struct tty *);
182 static inline void com_stsoft(struct com_softc *, struct tty *);
183 static inline void com_schedrx(struct com_softc *);
184 void	comdiag(void *);
185 
186 dev_type_open(comopen);
187 dev_type_close(comclose);
188 dev_type_read(comread);
189 dev_type_write(comwrite);
190 dev_type_ioctl(comioctl);
191 dev_type_stop(comstop);
192 dev_type_tty(comtty);
193 dev_type_poll(compoll);
194 
195 static struct comcons_info comcons_info;
196 
197 /*
198  * Following are all routines needed for COM to act as console
199  */
200 static struct consdev comcons = {
201 	.cn_getc = comcngetc,
202 	.cn_putc = comcnputc,
203 	.cn_pollc = comcnpollc,
204 	.cn_dev = NODEV,
205 	.cn_pri = CN_NORMAL
206 };
207 
208 
209 const struct cdevsw com_cdevsw = {
210 	.d_open = comopen,
211 	.d_close = comclose,
212 	.d_read = comread,
213 	.d_write = comwrite,
214 	.d_ioctl = comioctl,
215 	.d_stop = comstop,
216 	.d_tty = comtty,
217 	.d_poll = compoll,
218 	.d_mmap = nommap,
219 	.d_kqfilter = ttykqfilter,
220 	.d_discard = nodiscard,
221 	.d_flag = D_TTY
222 };
223 
224 /*
225  * Make this an option variable one can patch.
226  * But be warned:  this must be a power of 2!
227  */
228 u_int com_rbuf_size = COM_RING_SIZE;
229 
230 /* Stop input when 3/4 of the ring is full; restart when only 1/4 is full. */
231 u_int com_rbuf_hiwat = (COM_RING_SIZE * 1) / 4;
232 u_int com_rbuf_lowat = (COM_RING_SIZE * 3) / 4;
233 
234 static int comconsattached;
235 static struct cnm_state com_cnm_state;
236 
237 #ifdef KGDB
238 #include <sys/kgdb.h>
239 
240 static struct com_regs comkgdbregs;
241 static int com_kgdb_attached;
242 
243 int	com_kgdb_getc(void *);
244 void	com_kgdb_putc(void *, int);
245 #endif /* KGDB */
246 
247 /* initializer for typical 16550-ish hardware */
248 static const bus_size_t com_std_map[COM_REGMAP_NENTRIES] = {
249 	[COM_REG_RXDATA]	=	com_data,
250 	[COM_REG_TXDATA]	=	com_data,
251 	[COM_REG_DLBL]		=	com_dlbl,
252 	[COM_REG_DLBH]		=	com_dlbh,
253 	[COM_REG_IER]		=	com_ier,
254 	[COM_REG_IIR]		=	com_iir,
255 	[COM_REG_FIFO]		=	com_fifo,
256 	[COM_REG_TCR]		=	com_fifo,
257 	[COM_REG_EFR]		=	com_efr,
258 	[COM_REG_TLR]		=	com_efr,
259 	[COM_REG_LCR]		=	com_lcr,
260 	[COM_REG_MCR]		=	com_mcr,
261 	[COM_REG_LSR]		=	com_lsr,
262 	[COM_REG_MSR]		=	com_msr,
263 	[COM_REG_USR]		=	com_usr,
264 	[COM_REG_TFL]		=	com_tfl,
265 	[COM_REG_RFL]		=	com_rfl,
266 	[COM_REG_HALT]		=	com_halt,
267 	[COM_REG_MDR1]		=	com_mdr1,
268 };
269 
270 #define	COMDIALOUT_MASK	TTDIALOUT_MASK
271 
272 #define	COMUNIT(x)	TTUNIT(x)
273 #define	COMDIALOUT(x)	TTDIALOUT(x)
274 
275 #define	COM_ISALIVE(sc)	((sc)->enabled != 0 && \
276 			 device_is_active((sc)->sc_dev))
277 
278 #define	BR	BUS_SPACE_BARRIER_READ
279 #define	BW	BUS_SPACE_BARRIER_WRITE
280 #define COM_BARRIER(r, f) \
281 	bus_space_barrier((r)->cr_iot, (r)->cr_ioh, 0, (r)->cr_nports, (f))
282 
283 /*
284  * com_read_1 --
285  *	Default register read callback using single byte accesses.
286  */
287 static uint8_t
288 com_read_1(struct com_regs *regs, u_int reg)
289 {
290 	return bus_space_read_1(regs->cr_iot, regs->cr_ioh, reg);
291 }
292 
293 /*
294  * com_write_1 --
295  *	Default register write callback using single byte accesses.
296  */
297 static void
298 com_write_1(struct com_regs *regs, u_int reg, uint8_t val)
299 {
300 	bus_space_write_1(regs->cr_iot, regs->cr_ioh, reg, val);
301 }
302 
303 /*
304  * com_write_multi_1 --
305  *	Default register multi write callback using single byte accesses.
306  */
307 static void
308 com_write_multi_1(struct com_regs *regs, u_int reg, const uint8_t *datap,
309     bus_size_t count)
310 {
311 	bus_space_write_multi_1(regs->cr_iot, regs->cr_ioh, reg, datap, count);
312 }
313 
314 /*
315  * com_read_4 --
316  *	Default register read callback using dword accesses.
317  */
318 static uint8_t
319 com_read_4(struct com_regs *regs, u_int reg)
320 {
321 	return bus_space_read_4(regs->cr_iot, regs->cr_ioh, reg) & 0xff;
322 }
323 
324 /*
325  * com_write_4 --
326  *	Default register write callback using dword accesses.
327  */
328 static void
329 com_write_4(struct com_regs *regs, u_int reg, uint8_t val)
330 {
331 	bus_space_write_4(regs->cr_iot, regs->cr_ioh, reg, val);
332 }
333 
334 /*
335  * com_write_multi_4 --
336  *	Default register multi write callback using dword accesses.
337  */
338 static void
339 com_write_multi_4(struct com_regs *regs, u_int reg, const uint8_t *datap,
340     bus_size_t count)
341 {
342 	while (count-- > 0) {
343 		bus_space_write_4(regs->cr_iot, regs->cr_ioh, reg, *datap++);
344 	}
345 }
346 
347 /*
348  * com_init_regs --
349  *	Driver front-ends use this to initialize our register map
350  *	in the standard fashion.  They may then tailor the map to
351  *	their own particular requirements.
352  */
353 void
354 com_init_regs(struct com_regs *regs, bus_space_tag_t st, bus_space_handle_t sh,
355 	      bus_addr_t addr)
356 {
357 
358 	memset(regs, 0, sizeof(*regs));
359 	regs->cr_iot = st;
360 	regs->cr_ioh = sh;
361 	regs->cr_iobase = addr;
362 	regs->cr_nports = COM_NPORTS;
363 	regs->cr_read = com_read_1;
364 	regs->cr_write = com_write_1;
365 	regs->cr_write_multi = com_write_multi_1;
366 	memcpy(regs->cr_map, com_std_map, sizeof(regs->cr_map));
367 }
368 
369 /*
370  * com_init_regs_stride --
371  *	Convenience function for front-ends that have a stride between
372  *	registers.
373  */
374 void
375 com_init_regs_stride(struct com_regs *regs, bus_space_tag_t st,
376 		     bus_space_handle_t sh, bus_addr_t addr, u_int regshift)
377 {
378 
379 	com_init_regs(regs, st, sh, addr);
380 	for (size_t i = 0; i < __arraycount(regs->cr_map); i++) {
381 		regs->cr_map[i] <<= regshift;
382 	}
383 	regs->cr_nports <<= regshift;
384 }
385 
386 /*
387  * com_init_regs_stride_width --
388  *	Convenience function for front-ends that have a stride between
389  *	registers and specific I/O width requirements.
390  */
391 void
392 com_init_regs_stride_width(struct com_regs *regs, bus_space_tag_t st,
393 			   bus_space_handle_t sh, bus_addr_t addr,
394 			   u_int regshift, u_int width)
395 {
396 
397 	com_init_regs(regs, st, sh, addr);
398 	for (size_t i = 0; i < __arraycount(regs->cr_map); i++) {
399 		regs->cr_map[i] <<= regshift;
400 	}
401 	regs->cr_nports <<= regshift;
402 
403 	switch (width) {
404 	case 1:
405 		/* Already set by com_init_regs */
406 		break;
407 	case 4:
408 		regs->cr_read = com_read_4;
409 		regs->cr_write = com_write_4;
410 		regs->cr_write_multi = com_write_multi_4;
411 		break;
412 	default:
413 		panic("com: unsupported I/O width %d", width);
414 	}
415 }
416 
417 /*ARGSUSED*/
418 int
419 comspeed(long speed, long frequency, int type)
420 {
421 #define	divrnd(n, q)	(((n)*2/(q)+1)/2)	/* divide and round off */
422 
423 	int x, err;
424 	int divisor = 16;
425 
426 	if ((type == COM_TYPE_OMAP) && (speed > 230400)) {
427 	    divisor = 13;
428 	}
429 
430 	if (speed == 0)
431 		return (0);
432 	if (speed < 0)
433 		return (-1);
434 	x = divrnd(frequency / divisor, speed);
435 	if (x <= 0)
436 		return (-1);
437 	err = divrnd(((quad_t)frequency) * 1000 / divisor, speed * x) - 1000;
438 	if (err < 0)
439 		err = -err;
440 	if (err > COM_TOLERANCE)
441 		return (-1);
442 	return (x);
443 
444 #undef	divrnd
445 }
446 
447 #ifdef COM_DEBUG
448 int	com_debug = 0;
449 
450 void comstatus(struct com_softc *, const char *);
451 void
452 comstatus(struct com_softc *sc, const char *str)
453 {
454 	struct tty *tp = sc->sc_tty;
455 
456 	aprint_normal_dev(sc->sc_dev,
457 	    "%s %cclocal  %cdcd %cts_carr_on %cdtr %ctx_stopped\n",
458 	    str,
459 	    ISSET(tp->t_cflag, CLOCAL) ? '+' : '-',
460 	    ISSET(sc->sc_msr, MSR_DCD) ? '+' : '-',
461 	    ISSET(tp->t_state, TS_CARR_ON) ? '+' : '-',
462 	    ISSET(sc->sc_mcr, MCR_DTR) ? '+' : '-',
463 	    sc->sc_tx_stopped ? '+' : '-');
464 
465 	aprint_normal_dev(sc->sc_dev,
466 	    "%s %ccrtscts %ccts %cts_ttstop  %crts rx_flags=0x%x\n",
467 	    str,
468 	    ISSET(tp->t_cflag, CRTSCTS) ? '+' : '-',
469 	    ISSET(sc->sc_msr, MSR_CTS) ? '+' : '-',
470 	    ISSET(tp->t_state, TS_TTSTOP) ? '+' : '-',
471 	    ISSET(sc->sc_mcr, MCR_RTS) ? '+' : '-',
472 	    sc->sc_rx_flags);
473 }
474 #endif
475 
476 int
477 com_probe_subr(struct com_regs *regs)
478 {
479 
480 	/* force access to id reg */
481 	CSR_WRITE_1(regs, COM_REG_LCR, LCR_8BITS);
482 	CSR_WRITE_1(regs, COM_REG_IIR, 0);
483 	if ((CSR_READ_1(regs, COM_REG_LCR) != LCR_8BITS) ||
484 	    (CSR_READ_1(regs, COM_REG_IIR) & 0x38))
485 		return (0);
486 
487 	return (1);
488 }
489 
490 int
491 comprobe1(bus_space_tag_t iot, bus_space_handle_t ioh)
492 {
493 	struct com_regs	regs;
494 
495 	com_init_regs(&regs, iot, ioh, 0/*XXX*/);
496 
497 	return com_probe_subr(&regs);
498 }
499 
500 /*
501  * No locking in this routine; it is only called during attach,
502  * or with the port already locked.
503  */
504 static void
505 com_enable_debugport(struct com_softc *sc)
506 {
507 
508 	/* Turn on line break interrupt, set carrier. */
509 	sc->sc_ier = IER_ERLS;
510 	if (sc->sc_type == COM_TYPE_PXA2x0)
511 		sc->sc_ier |= IER_EUART | IER_ERXTOUT;
512 	if (sc->sc_type == COM_TYPE_INGENIC ||
513 	    sc->sc_type == COM_TYPE_TEGRA)
514 		sc->sc_ier |= IER_ERXTOUT;
515 	CSR_WRITE_1(&sc->sc_regs, COM_REG_IER, sc->sc_ier);
516 	SET(sc->sc_mcr, MCR_DTR | MCR_RTS);
517 	CSR_WRITE_1(&sc->sc_regs, COM_REG_MCR, sc->sc_mcr);
518 }
519 
520 static void
521 com_intr_poll(void *arg)
522 {
523 	struct com_softc * const sc = arg;
524 
525 	comintr(sc);
526 
527 	callout_schedule(&sc->sc_poll_callout, sc->sc_poll_ticks);
528 }
529 
530 void
531 com_attach_subr(struct com_softc *sc)
532 {
533 	struct com_regs *regsp = &sc->sc_regs;
534 	struct tty *tp;
535 	uint32_t cpr;
536 	uint8_t lcr;
537 	const char *fifo_msg = NULL;
538 	prop_dictionary_t dict;
539 	bool is_console = true;
540 	bool force_console = false;
541 
542 	aprint_naive("\n");
543 
544 	dict = device_properties(sc->sc_dev);
545 	prop_dictionary_get_bool(dict, "is_console", &is_console);
546 	prop_dictionary_get_bool(dict, "force_console", &force_console);
547 	callout_init(&sc->sc_diag_callout, 0);
548 	callout_init(&sc->sc_poll_callout, 0);
549 	callout_setfunc(&sc->sc_poll_callout, com_intr_poll, sc);
550 	mutex_init(&sc->sc_lock, MUTEX_DEFAULT, IPL_HIGH);
551 
552 #if defined(COM_16650)
553 	sc->sc_type = COM_TYPE_16650;
554 #elif defined(COM_16750)
555 	sc->sc_type = COM_TYPE_16750;
556 #elif defined(COM_HAYESP)
557 	sc->sc_type = COM_TYPE_HAYESP;
558 #elif defined(COM_PXA2X0)
559 	sc->sc_type = COM_TYPE_PXA2x0;
560 #endif
561 
562 	/* Disable interrupts before configuring the device. */
563 	if (sc->sc_type == COM_TYPE_PXA2x0)
564 		sc->sc_ier = IER_EUART;
565 	else
566 		sc->sc_ier = 0;
567 
568 	CSR_WRITE_1(regsp, COM_REG_IER, sc->sc_ier);
569 
570 	if ((bus_space_is_equal(regsp->cr_iot, comcons_info.regs.cr_iot) &&
571 	    regsp->cr_iobase == comcons_info.regs.cr_iobase) || force_console) {
572 		comconsattached = 1;
573 
574 		if (force_console)
575 			memcpy(regsp, &comcons_info.regs, sizeof(*regsp));
576 
577 		if (cn_tab == NULL && comcnreattach() != 0) {
578 			printf("can't re-init serial console @%lx\n",
579 			    (u_long)comcons_info.regs.cr_iobase);
580 		}
581 
582 		switch (sc->sc_type) {
583 		case COM_TYPE_16750:
584 		case COM_TYPE_DW_APB:
585 			/* Use in comintr(). */
586  			sc->sc_lcr = cflag2lcr(comcons_info.cflag);
587 			break;
588 		}
589 
590 		/* Make sure the console is always "hardwired". */
591 		delay(10000);			/* wait for output to finish */
592 		if (is_console) {
593 			SET(sc->sc_hwflags, COM_HW_CONSOLE);
594 		}
595 
596 		SET(sc->sc_swflags, TIOCFLAG_SOFTCAR);
597 	}
598 
599 	/* Probe for FIFO */
600 	switch (sc->sc_type) {
601 	case COM_TYPE_HAYESP:
602 		goto fifodone;
603 
604 	case COM_TYPE_AU1x00:
605 		sc->sc_fifolen = 16;
606 		fifo_msg = "Au1X00 UART";
607 		SET(sc->sc_hwflags, COM_HW_FIFO);
608 		goto fifodelay;
609 
610 	case COM_TYPE_16550_NOERS:
611 		sc->sc_fifolen = 16;
612 		fifo_msg = "ns16650, no ERS";
613 		SET(sc->sc_hwflags, COM_HW_FIFO);
614 		goto fifodelay;
615 
616 	case COM_TYPE_OMAP:
617 		sc->sc_fifolen = 64;
618 		fifo_msg = "OMAP UART";
619 		SET(sc->sc_hwflags, COM_HW_FIFO);
620 		goto fifodelay;
621 
622 	case COM_TYPE_INGENIC:
623 		sc->sc_fifolen = 16;
624 		fifo_msg = "Ingenic UART";
625 		SET(sc->sc_hwflags, COM_HW_FIFO);
626 		SET(sc->sc_hwflags, COM_HW_NOIEN);
627 		goto fifodelay;
628 
629 	case COM_TYPE_TEGRA:
630 		sc->sc_fifolen = 8;
631 		fifo_msg = "Tegra UART";
632 		SET(sc->sc_hwflags, COM_HW_FIFO);
633 		CSR_WRITE_1(regsp, COM_REG_FIFO,
634 		    FIFO_ENABLE | FIFO_RCV_RST | FIFO_XMT_RST | FIFO_TRIGGER_1);
635 		goto fifodelay;
636 
637 	case COM_TYPE_BCMAUXUART:
638 		sc->sc_fifolen = 1;
639 		fifo_msg = "BCM AUX UART";
640 		SET(sc->sc_hwflags, COM_HW_FIFO);
641 		CSR_WRITE_1(regsp, COM_REG_FIFO,
642 		    FIFO_ENABLE | FIFO_RCV_RST | FIFO_XMT_RST | FIFO_TRIGGER_1);
643 		goto fifodelay;
644 
645 	case COM_TYPE_DW_APB:
646 		if (!prop_dictionary_get_uint(dict, "fifolen", &sc->sc_fifolen)) {
647 			cpr = bus_space_read_4(sc->sc_regs.cr_iot,
648 			    sc->sc_regs.cr_ioh, DW_APB_UART_CPR);
649 			sc->sc_fifolen = __SHIFTOUT(cpr, UART_CPR_FIFO_MODE) * 16;
650 		}
651 		if (sc->sc_fifolen == 0) {
652 			sc->sc_fifolen = 1;
653 			fifo_msg = "DesignWare APB UART, no fifo";
654 			CSR_WRITE_1(regsp, COM_REG_FIFO, 0);
655 		} else {
656 			fifo_msg = "DesignWare APB UART";
657 			SET(sc->sc_hwflags, COM_HW_FIFO);
658 			CSR_WRITE_1(regsp, COM_REG_FIFO,
659 			    FIFO_ENABLE | FIFO_RCV_RST | FIFO_XMT_RST | FIFO_TRIGGER_1);
660 		}
661 		goto fifodelay;
662 	}
663 
664 	sc->sc_fifolen = 1;
665 	/* look for a NS 16550AF UART with FIFOs */
666 	if (sc->sc_type == COM_TYPE_INGENIC) {
667 		CSR_WRITE_1(regsp, COM_REG_FIFO,
668 		    FIFO_ENABLE | FIFO_RCV_RST | FIFO_XMT_RST |
669 		    FIFO_TRIGGER_14 | FIFO_UART_ON);
670 	} else
671 		CSR_WRITE_1(regsp, COM_REG_FIFO,
672 		    FIFO_ENABLE | FIFO_RCV_RST | FIFO_XMT_RST | FIFO_TRIGGER_14);
673 	delay(100);
674 	if (ISSET(CSR_READ_1(regsp, COM_REG_IIR), IIR_FIFO_MASK)
675 	    == IIR_FIFO_MASK)
676 		if (ISSET(CSR_READ_1(regsp, COM_REG_FIFO), FIFO_TRIGGER_14)
677 		    == FIFO_TRIGGER_14) {
678 			SET(sc->sc_hwflags, COM_HW_FIFO);
679 
680 			fifo_msg = "ns16550a";
681 			sc->sc_fifolen = 16;
682 
683 			/*
684 			 * IIR changes into the EFR if LCR is set to LCR_EERS
685 			 * on 16650s. We also know IIR != 0 at this point.
686 			 * Write 0 into the EFR, and read it. If the result
687 			 * is 0, we have a 16650.
688 			 *
689 			 * Older 16650s were broken; the test to detect them
690 			 * is taken from the Linux driver. Apparently
691 			 * setting DLAB enable gives access to the EFR on
692 			 * these chips.
693 			 */
694 			if (sc->sc_type == COM_TYPE_16650) {
695 				lcr = CSR_READ_1(regsp, COM_REG_LCR);
696 				CSR_WRITE_1(regsp, COM_REG_LCR, LCR_EERS);
697 				CSR_WRITE_1(regsp, COM_REG_EFR, 0);
698 				if (CSR_READ_1(regsp, COM_REG_EFR) == 0) {
699 					CSR_WRITE_1(regsp, COM_REG_LCR,
700 					    lcr | LCR_DLAB);
701 					if (CSR_READ_1(regsp, COM_REG_EFR) == 0) {
702 						CLR(sc->sc_hwflags, COM_HW_FIFO);
703 						sc->sc_fifolen = 0;
704 					} else {
705 						SET(sc->sc_hwflags, COM_HW_FLOW);
706 						sc->sc_fifolen = 32;
707 					}
708 				} else
709 					sc->sc_fifolen = 16;
710 
711 				CSR_WRITE_1(regsp, COM_REG_LCR, lcr);
712 				if (sc->sc_fifolen == 0)
713 					fifo_msg = "st16650, broken fifo";
714 				else if (sc->sc_fifolen == 32)
715 					fifo_msg = "st16650a";
716 				else
717 					fifo_msg = "ns16550a";
718 			}
719 
720 			/*
721 			 * TL16C750 can enable 64byte FIFO, only when DLAB
722 			 * is 1.  However, some 16750 may always enable.  For
723 			 * example, restrictions according to DLAB in a data
724 			 * sheet for SC16C750 were not described.
725 			 * Please enable 'options COM_16650', supposing you
726 			 * use SC16C750.  Probably 32 bytes of FIFO and HW FLOW
727 			 * should become effective.
728 			 */
729 			if (sc->sc_type == COM_TYPE_16750) {
730 				uint8_t iir1, iir2;
731 				uint8_t fcr = FIFO_ENABLE | FIFO_TRIGGER_14;
732 
733 				lcr = CSR_READ_1(regsp, COM_REG_LCR);
734 				CSR_WRITE_1(regsp, COM_REG_LCR,
735 				    lcr & ~LCR_DLAB);
736 				CSR_WRITE_1(regsp, COM_REG_FIFO,
737 				    fcr | FIFO_64B_ENABLE);
738 				iir1 = CSR_READ_1(regsp, COM_REG_IIR);
739 				CSR_WRITE_1(regsp, COM_REG_FIFO, fcr);
740 				CSR_WRITE_1(regsp, COM_REG_LCR, lcr | LCR_DLAB);
741 				CSR_WRITE_1(regsp, COM_REG_FIFO,
742 				    fcr | FIFO_64B_ENABLE);
743 				iir2 = CSR_READ_1(regsp, COM_REG_IIR);
744 
745 				CSR_WRITE_1(regsp, COM_REG_LCR, lcr);
746 
747 				if (!ISSET(iir1, IIR_64B_FIFO) &&
748 				    ISSET(iir2, IIR_64B_FIFO)) {
749 					/* It is TL16C750. */
750 					sc->sc_fifolen = 64;
751 					SET(sc->sc_hwflags, COM_HW_AFE);
752 				} else
753 					CSR_WRITE_1(regsp, COM_REG_FIFO, fcr);
754 
755 				if (sc->sc_fifolen == 64)
756 					fifo_msg = "tl16c750";
757 				else
758 					fifo_msg = "ns16750";
759 			}
760 		} else
761 			fifo_msg = "ns16550, broken fifo";
762 	else
763 		fifo_msg = "ns8250 or ns16450, no fifo";
764 	CSR_WRITE_1(regsp, COM_REG_FIFO, 0);
765 
766 fifodelay:
767 	/*
768 	 * Some chips will clear down both Tx and Rx FIFOs when zero is
769 	 * written to com_fifo. If this chip is the console, writing zero
770 	 * results in some of the chip/FIFO description being lost, so delay
771 	 * printing it until now.
772 	 */
773 	delay(10);
774 	if (ISSET(sc->sc_hwflags, COM_HW_FIFO)) {
775 		aprint_normal(": %s, %d-byte FIFO\n", fifo_msg, sc->sc_fifolen);
776 	} else {
777 		aprint_normal(": %s\n", fifo_msg);
778 	}
779 	if (ISSET(sc->sc_hwflags, COM_HW_TXFIFO_DISABLE)) {
780 		sc->sc_fifolen = 1;
781 		aprint_normal_dev(sc->sc_dev, "txfifo disabled\n");
782 	}
783 
784 fifodone:
785 
786 	tp = tty_alloc();
787 	tp->t_oproc = comstart;
788 	tp->t_param = comparam;
789 	tp->t_hwiflow = comhwiflow;
790 	tp->t_softc = sc;
791 
792 	sc->sc_tty = tp;
793 	sc->sc_rbuf = malloc(com_rbuf_size << 1, M_DEVBUF, M_WAITOK);
794 	sc->sc_rbput = sc->sc_rbget = sc->sc_rbuf;
795 	sc->sc_rbavail = com_rbuf_size;
796 	sc->sc_ebuf = sc->sc_rbuf + (com_rbuf_size << 1);
797 
798 	tty_attach(tp);
799 
800 	if (!ISSET(sc->sc_hwflags, COM_HW_NOIEN))
801 		SET(sc->sc_mcr, MCR_IENABLE);
802 
803 	if (ISSET(sc->sc_hwflags, COM_HW_CONSOLE)) {
804 		int maj;
805 
806 		/* locate the major number */
807 		maj = cdevsw_lookup_major(&com_cdevsw);
808 
809 		tp->t_dev = cn_tab->cn_dev = makedev(maj,
810 						     device_unit(sc->sc_dev));
811 
812 		aprint_normal_dev(sc->sc_dev, "console\n");
813 	}
814 
815 #ifdef KGDB
816 	/*
817 	 * Allow kgdb to "take over" this port.  If this is
818 	 * not the console and is the kgdb device, it has
819 	 * exclusive use.  If it's the console _and_ the
820 	 * kgdb device, it doesn't.
821 	 */
822 	if (bus_space_is_equal(regsp->cr_iot, comkgdbregs.cr_iot) &&
823 	    regsp->cr_iobase == comkgdbregs.cr_iobase) {
824 		if (!ISSET(sc->sc_hwflags, COM_HW_CONSOLE)) {
825 			com_kgdb_attached = 1;
826 
827 			SET(sc->sc_hwflags, COM_HW_KGDB);
828 		}
829 		aprint_normal_dev(sc->sc_dev, "kgdb\n");
830 	}
831 #endif
832 
833 	sc->sc_si = softint_establish(SOFTINT_SERIAL, comsoft, sc);
834 
835 #ifdef RND_COM
836 	rnd_attach_source(&sc->rnd_source, device_xname(sc->sc_dev),
837 			  RND_TYPE_TTY, RND_FLAG_DEFAULT);
838 #endif
839 
840 	/* if there are no enable/disable functions, assume the device
841 	   is always enabled */
842 	if (!sc->enable)
843 		sc->enabled = 1;
844 
845 	com_config(sc);
846 
847 	SET(sc->sc_hwflags, COM_HW_DEV_OK);
848 
849 	if (sc->sc_poll_ticks != 0)
850 		callout_schedule(&sc->sc_poll_callout, sc->sc_poll_ticks);
851 }
852 
853 void
854 com_config(struct com_softc *sc)
855 {
856 	struct com_regs *regsp = &sc->sc_regs;
857 
858 	/* Disable interrupts before configuring the device. */
859 	if (sc->sc_type == COM_TYPE_PXA2x0)
860 		sc->sc_ier = IER_EUART;
861 	else
862 		sc->sc_ier = 0;
863 	CSR_WRITE_1(regsp, COM_REG_IER, sc->sc_ier);
864 	(void) CSR_READ_1(regsp, COM_REG_IIR);
865 
866 	/* Look for a Hayes ESP board. */
867 	if (sc->sc_type == COM_TYPE_HAYESP) {
868 
869 		/* Set 16550 compatibility mode */
870 		bus_space_write_1(regsp->cr_iot, sc->sc_hayespioh, HAYESP_CMD1,
871 				  HAYESP_SETMODE);
872 		bus_space_write_1(regsp->cr_iot, sc->sc_hayespioh, HAYESP_CMD2,
873 				  HAYESP_MODE_FIFO|HAYESP_MODE_RTS|
874 				  HAYESP_MODE_SCALE);
875 
876 		/* Set RTS/CTS flow control */
877 		bus_space_write_1(regsp->cr_iot, sc->sc_hayespioh, HAYESP_CMD1,
878 				  HAYESP_SETFLOWTYPE);
879 		bus_space_write_1(regsp->cr_iot, sc->sc_hayespioh, HAYESP_CMD2,
880 				  HAYESP_FLOW_RTS);
881 		bus_space_write_1(regsp->cr_iot, sc->sc_hayespioh, HAYESP_CMD2,
882 				  HAYESP_FLOW_CTS);
883 
884 		/* Set flow control levels */
885 		bus_space_write_1(regsp->cr_iot, sc->sc_hayespioh, HAYESP_CMD1,
886 				  HAYESP_SETRXFLOW);
887 		bus_space_write_1(regsp->cr_iot, sc->sc_hayespioh, HAYESP_CMD2,
888 				  HAYESP_HIBYTE(HAYESP_RXHIWMARK));
889 		bus_space_write_1(regsp->cr_iot, sc->sc_hayespioh, HAYESP_CMD2,
890 				  HAYESP_LOBYTE(HAYESP_RXHIWMARK));
891 		bus_space_write_1(regsp->cr_iot, sc->sc_hayespioh, HAYESP_CMD2,
892 				  HAYESP_HIBYTE(HAYESP_RXLOWMARK));
893 		bus_space_write_1(regsp->cr_iot, sc->sc_hayespioh, HAYESP_CMD2,
894 				  HAYESP_LOBYTE(HAYESP_RXLOWMARK));
895 	}
896 
897 	if (ISSET(sc->sc_hwflags, COM_HW_CONSOLE|COM_HW_KGDB))
898 		com_enable_debugport(sc);
899 }
900 
901 int
902 com_detach(device_t self, int flags)
903 {
904 	struct com_softc *sc = device_private(self);
905 	int maj, mn;
906 
907 	if (ISSET(sc->sc_hwflags, COM_HW_KGDB))
908 		return EBUSY;
909 
910 	if (ISSET(sc->sc_hwflags, COM_HW_CONSOLE) &&
911 	    (flags & DETACH_SHUTDOWN) != 0)
912 		return EBUSY;
913 
914 	if (sc->disable != NULL && sc->enabled != 0) {
915 		(*sc->disable)(sc);
916 		sc->enabled = 0;
917 	}
918 
919 	if (ISSET(sc->sc_hwflags, COM_HW_CONSOLE)) {
920 		comconsattached = 0;
921 		cn_tab = NULL;
922 	}
923 
924 	/* locate the major number */
925 	maj = cdevsw_lookup_major(&com_cdevsw);
926 
927 	/* Nuke the vnodes for any open instances. */
928 	mn = device_unit(self);
929 	vdevgone(maj, mn, mn, VCHR);
930 
931 	mn |= COMDIALOUT_MASK;
932 	vdevgone(maj, mn, mn, VCHR);
933 
934 	if (sc->sc_rbuf == NULL) {
935 		/*
936 		 * Ring buffer allocation failed in the com_attach_subr,
937 		 * only the tty is allocated, and nothing else.
938 		 */
939 		tty_free(sc->sc_tty);
940 		return 0;
941 	}
942 
943 	/* Free the receive buffer. */
944 	free(sc->sc_rbuf, M_DEVBUF);
945 
946 	/* Detach and free the tty. */
947 	tty_detach(sc->sc_tty);
948 	tty_free(sc->sc_tty);
949 
950 	/* Unhook the soft interrupt handler. */
951 	softint_disestablish(sc->sc_si);
952 
953 #ifdef RND_COM
954 	/* Unhook the entropy source. */
955 	rnd_detach_source(&sc->rnd_source);
956 #endif
957 	callout_destroy(&sc->sc_diag_callout);
958 
959 	/* Destroy the lock. */
960 	mutex_destroy(&sc->sc_lock);
961 
962 	return (0);
963 }
964 
965 void
966 com_shutdown(struct com_softc *sc)
967 {
968 	struct tty *tp = sc->sc_tty;
969 
970 	mutex_spin_enter(&sc->sc_lock);
971 
972 	/* If we were asserting flow control, then deassert it. */
973 	SET(sc->sc_rx_flags, RX_IBUF_BLOCKED);
974 	com_hwiflow(sc);
975 
976 	/* Clear any break condition set with TIOCSBRK. */
977 	com_break(sc, 0);
978 
979 	/*
980 	 * Hang up if necessary.  Record when we hung up, so if we
981 	 * immediately open the port again, we will wait a bit until
982 	 * the other side has had time to notice that we hung up.
983 	 */
984 	if (ISSET(tp->t_cflag, HUPCL)) {
985 		com_modem(sc, 0);
986 		microuptime(&sc->sc_hup_pending);
987 		sc->sc_hup_pending.tv_sec++;
988 	}
989 
990 	/* Turn off interrupts. */
991 	if (ISSET(sc->sc_hwflags, COM_HW_CONSOLE)) {
992 		sc->sc_ier = IER_ERLS; /* interrupt on line break */
993 		if ((sc->sc_type == COM_TYPE_PXA2x0) ||
994 		    (sc->sc_type == COM_TYPE_INGENIC) ||
995 		    (sc->sc_type == COM_TYPE_TEGRA))
996 			sc->sc_ier |= IER_ERXTOUT;
997 	} else
998 		sc->sc_ier = 0;
999 
1000 	if (sc->sc_type == COM_TYPE_PXA2x0)
1001 		sc->sc_ier |= IER_EUART;
1002 
1003 	CSR_WRITE_1(&sc->sc_regs, COM_REG_IER, sc->sc_ier);
1004 
1005 	mutex_spin_exit(&sc->sc_lock);
1006 
1007 	if (sc->disable) {
1008 #ifdef DIAGNOSTIC
1009 		if (!sc->enabled)
1010 			panic("com_shutdown: not enabled?");
1011 #endif
1012 		(*sc->disable)(sc);
1013 		sc->enabled = 0;
1014 	}
1015 }
1016 
1017 int
1018 comopen(dev_t dev, int flag, int mode, struct lwp *l)
1019 {
1020 	struct com_softc *sc;
1021 	struct tty *tp;
1022 	int s;
1023 	int error;
1024 
1025 	sc = device_lookup_private(&com_cd, COMUNIT(dev));
1026 	if (sc == NULL || !ISSET(sc->sc_hwflags, COM_HW_DEV_OK) ||
1027 		sc->sc_rbuf == NULL)
1028 		return (ENXIO);
1029 
1030 	if (!device_is_active(sc->sc_dev))
1031 		return (ENXIO);
1032 
1033 #ifdef KGDB
1034 	/*
1035 	 * If this is the kgdb port, no other use is permitted.
1036 	 */
1037 	if (ISSET(sc->sc_hwflags, COM_HW_KGDB))
1038 		return (EBUSY);
1039 #endif
1040 
1041 	tp = sc->sc_tty;
1042 
1043 	/*
1044 	 * If the device is exclusively for kernel use, deny userland
1045 	 * open.
1046 	 */
1047 	if (ISSET(tp->t_state, TS_KERN_ONLY))
1048 		return (EBUSY);
1049 
1050 	if (kauth_authorize_device_tty(l->l_cred, KAUTH_DEVICE_TTY_OPEN, tp))
1051 		return (EBUSY);
1052 
1053 	s = spltty();
1054 
1055 	/*
1056 	 * Do the following iff this is a first open.
1057 	 */
1058 	if (!ISSET(tp->t_state, TS_ISOPEN) && tp->t_wopen == 0) {
1059 		struct termios t;
1060 		struct timeval now, diff;
1061 
1062 		tp->t_dev = dev;
1063 
1064 		if (sc->enable) {
1065 			if ((*sc->enable)(sc)) {
1066 				splx(s);
1067 				aprint_error_dev(sc->sc_dev,
1068 				    "device enable failed\n");
1069 				return (EIO);
1070 			}
1071 			mutex_spin_enter(&sc->sc_lock);
1072 			sc->enabled = 1;
1073 			com_config(sc);
1074 		} else {
1075 			mutex_spin_enter(&sc->sc_lock);
1076 		}
1077 
1078 		if (timerisset(&sc->sc_hup_pending)) {
1079 			microuptime(&now);
1080 			while (timercmp(&now, &sc->sc_hup_pending, <)) {
1081 				timersub(&sc->sc_hup_pending, &now, &diff);
1082 				const int ms = diff.tv_sec * 1000 +
1083 				    diff.tv_usec / 1000;
1084 				kpause(ttclos, false, uimax(mstohz(ms), 1),
1085 				    &sc->sc_lock);
1086 				microuptime(&now);
1087 			}
1088 			timerclear(&sc->sc_hup_pending);
1089 		}
1090 
1091 		/* Turn on interrupts. */
1092 		sc->sc_ier = IER_ERXRDY | IER_ERLS;
1093 		if (!ISSET(tp->t_cflag, CLOCAL))
1094 			sc->sc_ier |= IER_EMSC;
1095 
1096 		if (sc->sc_type == COM_TYPE_PXA2x0)
1097 			sc->sc_ier |= IER_EUART | IER_ERXTOUT;
1098 		else if (sc->sc_type == COM_TYPE_INGENIC ||
1099 			 sc->sc_type == COM_TYPE_TEGRA)
1100 			sc->sc_ier |= IER_ERXTOUT;
1101 		CSR_WRITE_1(&sc->sc_regs, COM_REG_IER, sc->sc_ier);
1102 
1103 		/* Fetch the current modem control status, needed later. */
1104 		sc->sc_msr = CSR_READ_1(&sc->sc_regs, COM_REG_MSR);
1105 
1106 		/* Clear PPS capture state on first open. */
1107 		mutex_spin_enter(&timecounter_lock);
1108 		memset(&sc->sc_pps_state, 0, sizeof(sc->sc_pps_state));
1109 		sc->sc_pps_state.ppscap = PPS_CAPTUREASSERT | PPS_CAPTURECLEAR;
1110 		pps_init(&sc->sc_pps_state);
1111 		mutex_spin_exit(&timecounter_lock);
1112 
1113 		mutex_spin_exit(&sc->sc_lock);
1114 
1115 		/*
1116 		 * Initialize the termios status to the defaults.  Add in the
1117 		 * sticky bits from TIOCSFLAGS.
1118 		 */
1119 		if (ISSET(sc->sc_hwflags, COM_HW_CONSOLE)) {
1120 			t.c_ospeed = comcons_info.rate;
1121 			t.c_cflag = comcons_info.cflag;
1122 		} else {
1123 			t.c_ospeed = TTYDEF_SPEED;
1124 			t.c_cflag = TTYDEF_CFLAG;
1125 		}
1126 		t.c_ispeed = t.c_ospeed;
1127 		if (ISSET(sc->sc_swflags, TIOCFLAG_CLOCAL))
1128 			SET(t.c_cflag, CLOCAL);
1129 		if (ISSET(sc->sc_swflags, TIOCFLAG_CRTSCTS))
1130 			SET(t.c_cflag, CRTSCTS);
1131 		if (ISSET(sc->sc_swflags, TIOCFLAG_MDMBUF))
1132 			SET(t.c_cflag, MDMBUF);
1133 		/* Make sure comparam() will do something. */
1134 		tp->t_ospeed = 0;
1135 		(void) comparam(tp, &t);
1136 		tp->t_iflag = TTYDEF_IFLAG;
1137 		tp->t_oflag = TTYDEF_OFLAG;
1138 		tp->t_lflag = TTYDEF_LFLAG;
1139 		ttychars(tp);
1140 		ttsetwater(tp);
1141 
1142 		mutex_spin_enter(&sc->sc_lock);
1143 
1144 		/*
1145 		 * Turn on DTR.  We must always do this, even if carrier is not
1146 		 * present, because otherwise we'd have to use TIOCSDTR
1147 		 * immediately after setting CLOCAL, which applications do not
1148 		 * expect.  We always assert DTR while the device is open
1149 		 * unless explicitly requested to deassert it.
1150 		 */
1151 		com_modem(sc, 1);
1152 
1153 		/* Clear the input ring, and unblock. */
1154 		sc->sc_rbput = sc->sc_rbget = sc->sc_rbuf;
1155 		sc->sc_rbavail = com_rbuf_size;
1156 		com_iflush(sc);
1157 		CLR(sc->sc_rx_flags, RX_ANY_BLOCK);
1158 		com_hwiflow(sc);
1159 
1160 #ifdef COM_DEBUG
1161 		if (com_debug)
1162 			comstatus(sc, "comopen  ");
1163 #endif
1164 
1165 		mutex_spin_exit(&sc->sc_lock);
1166 	}
1167 
1168 	splx(s);
1169 
1170 	error = ttyopen(tp, COMDIALOUT(dev), ISSET(flag, O_NONBLOCK));
1171 	if (error)
1172 		goto bad;
1173 
1174 	error = (*tp->t_linesw->l_open)(dev, tp);
1175 	if (error)
1176 		goto bad;
1177 
1178 	return (0);
1179 
1180 bad:
1181 	if (!ISSET(tp->t_state, TS_ISOPEN) && tp->t_wopen == 0) {
1182 		/*
1183 		 * We failed to open the device, and nobody else had it opened.
1184 		 * Clean up the state as appropriate.
1185 		 */
1186 		com_shutdown(sc);
1187 	}
1188 
1189 	return (error);
1190 }
1191 
1192 int
1193 comclose(dev_t dev, int flag, int mode, struct lwp *l)
1194 {
1195 	struct com_softc *sc =
1196 	    device_lookup_private(&com_cd, COMUNIT(dev));
1197 	struct tty *tp = sc->sc_tty;
1198 
1199 	/* XXX This is for cons.c. */
1200 	if (!ISSET(tp->t_state, TS_ISOPEN))
1201 		return (0);
1202 	/*
1203 	 * If the device is exclusively for kernel use, deny userland
1204 	 * close.
1205 	 */
1206 	if (ISSET(tp->t_state, TS_KERN_ONLY))
1207 		return (0);
1208 
1209 	(*tp->t_linesw->l_close)(tp, flag);
1210 	ttyclose(tp);
1211 
1212 	if (COM_ISALIVE(sc) == 0)
1213 		return (0);
1214 
1215 	if (!ISSET(tp->t_state, TS_ISOPEN) && tp->t_wopen == 0) {
1216 		/*
1217 		 * Although we got a last close, the device may still be in
1218 		 * use; e.g. if this was the dialout node, and there are still
1219 		 * processes waiting for carrier on the non-dialout node.
1220 		 */
1221 		com_shutdown(sc);
1222 	}
1223 
1224 	return (0);
1225 }
1226 
1227 int
1228 comread(dev_t dev, struct uio *uio, int flag)
1229 {
1230 	struct com_softc *sc =
1231 	    device_lookup_private(&com_cd, COMUNIT(dev));
1232 	struct tty *tp = sc->sc_tty;
1233 
1234 	if (COM_ISALIVE(sc) == 0)
1235 		return (EIO);
1236 
1237 	return ((*tp->t_linesw->l_read)(tp, uio, flag));
1238 }
1239 
1240 int
1241 comwrite(dev_t dev, struct uio *uio, int flag)
1242 {
1243 	struct com_softc *sc =
1244 	    device_lookup_private(&com_cd, COMUNIT(dev));
1245 	struct tty *tp = sc->sc_tty;
1246 
1247 	if (COM_ISALIVE(sc) == 0)
1248 		return (EIO);
1249 
1250 	return ((*tp->t_linesw->l_write)(tp, uio, flag));
1251 }
1252 
1253 int
1254 compoll(dev_t dev, int events, struct lwp *l)
1255 {
1256 	struct com_softc *sc =
1257 	    device_lookup_private(&com_cd, COMUNIT(dev));
1258 	struct tty *tp = sc->sc_tty;
1259 
1260 	if (COM_ISALIVE(sc) == 0)
1261 		return (POLLHUP);
1262 
1263 	return ((*tp->t_linesw->l_poll)(tp, events, l));
1264 }
1265 
1266 struct tty *
1267 comtty(dev_t dev)
1268 {
1269 	struct com_softc *sc =
1270 	    device_lookup_private(&com_cd, COMUNIT(dev));
1271 	struct tty *tp = sc->sc_tty;
1272 
1273 	return (tp);
1274 }
1275 
1276 int
1277 comioctl(dev_t dev, u_long cmd, void *data, int flag, struct lwp *l)
1278 {
1279 	struct com_softc *sc;
1280 	struct tty *tp;
1281 	int error;
1282 
1283 	sc = device_lookup_private(&com_cd, COMUNIT(dev));
1284 	if (sc == NULL)
1285 		return ENXIO;
1286 	if (COM_ISALIVE(sc) == 0)
1287 		return (EIO);
1288 
1289 	tp = sc->sc_tty;
1290 
1291 	error = (*tp->t_linesw->l_ioctl)(tp, cmd, data, flag, l);
1292 	if (error != EPASSTHROUGH)
1293 		return (error);
1294 
1295 	error = ttioctl(tp, cmd, data, flag, l);
1296 	if (error != EPASSTHROUGH)
1297 		return (error);
1298 
1299 	error = 0;
1300 	switch (cmd) {
1301 	case TIOCSFLAGS:
1302 		error = kauth_authorize_device_tty(l->l_cred,
1303 		    KAUTH_DEVICE_TTY_PRIVSET, tp);
1304 		break;
1305 	default:
1306 		/* nothing */
1307 		break;
1308 	}
1309 	if (error) {
1310 		return error;
1311 	}
1312 
1313 	mutex_spin_enter(&sc->sc_lock);
1314 
1315 	switch (cmd) {
1316 	case TIOCSBRK:
1317 		com_break(sc, 1);
1318 		break;
1319 
1320 	case TIOCCBRK:
1321 		com_break(sc, 0);
1322 		break;
1323 
1324 	case TIOCSDTR:
1325 		com_modem(sc, 1);
1326 		break;
1327 
1328 	case TIOCCDTR:
1329 		com_modem(sc, 0);
1330 		break;
1331 
1332 	case TIOCGFLAGS:
1333 		*(int *)data = sc->sc_swflags;
1334 		break;
1335 
1336 	case TIOCSFLAGS:
1337 		sc->sc_swflags = *(int *)data;
1338 		break;
1339 
1340 	case TIOCMSET:
1341 	case TIOCMBIS:
1342 	case TIOCMBIC:
1343 		tiocm_to_com(sc, cmd, *(int *)data);
1344 		break;
1345 
1346 	case TIOCMGET:
1347 		*(int *)data = com_to_tiocm(sc);
1348 		break;
1349 
1350 	case PPS_IOC_CREATE:
1351 	case PPS_IOC_DESTROY:
1352 	case PPS_IOC_GETPARAMS:
1353 	case PPS_IOC_SETPARAMS:
1354 	case PPS_IOC_GETCAP:
1355 	case PPS_IOC_FETCH:
1356 #ifdef PPS_SYNC
1357 	case PPS_IOC_KCBIND:
1358 #endif
1359 		mutex_spin_enter(&timecounter_lock);
1360 		error = pps_ioctl(cmd, data, &sc->sc_pps_state);
1361 		mutex_spin_exit(&timecounter_lock);
1362 		break;
1363 
1364 	case TIOCDCDTIMESTAMP:	/* XXX old, overloaded  API used by xntpd v3 */
1365 		mutex_spin_enter(&timecounter_lock);
1366 #ifndef PPS_TRAILING_EDGE
1367 		TIMESPEC_TO_TIMEVAL((struct timeval *)data,
1368 		    &sc->sc_pps_state.ppsinfo.assert_timestamp);
1369 #else
1370 		TIMESPEC_TO_TIMEVAL((struct timeval *)data,
1371 		    &sc->sc_pps_state.ppsinfo.clear_timestamp);
1372 #endif
1373 		mutex_spin_exit(&timecounter_lock);
1374 		break;
1375 
1376 	default:
1377 		error = EPASSTHROUGH;
1378 		break;
1379 	}
1380 
1381 	mutex_spin_exit(&sc->sc_lock);
1382 
1383 #ifdef COM_DEBUG
1384 	if (com_debug)
1385 		comstatus(sc, "comioctl ");
1386 #endif
1387 
1388 	return (error);
1389 }
1390 
1391 static inline void
1392 com_schedrx(struct com_softc *sc)
1393 {
1394 
1395 	sc->sc_rx_ready = 1;
1396 
1397 	/* Wake up the poller. */
1398 	softint_schedule(sc->sc_si);
1399 }
1400 
1401 void
1402 com_break(struct com_softc *sc, int onoff)
1403 {
1404 
1405 	if (onoff)
1406 		SET(sc->sc_lcr, LCR_SBREAK);
1407 	else
1408 		CLR(sc->sc_lcr, LCR_SBREAK);
1409 
1410 	if (!sc->sc_heldchange) {
1411 		if (sc->sc_tx_busy) {
1412 			sc->sc_heldtbc = sc->sc_tbc;
1413 			sc->sc_tbc = 0;
1414 			sc->sc_heldchange = 1;
1415 		} else
1416 			com_loadchannelregs(sc);
1417 	}
1418 }
1419 
1420 void
1421 com_modem(struct com_softc *sc, int onoff)
1422 {
1423 
1424 	if (sc->sc_mcr_dtr == 0)
1425 		return;
1426 
1427 	if (onoff)
1428 		SET(sc->sc_mcr, sc->sc_mcr_dtr);
1429 	else
1430 		CLR(sc->sc_mcr, sc->sc_mcr_dtr);
1431 
1432 	if (!sc->sc_heldchange) {
1433 		if (sc->sc_tx_busy) {
1434 			sc->sc_heldtbc = sc->sc_tbc;
1435 			sc->sc_tbc = 0;
1436 			sc->sc_heldchange = 1;
1437 		} else
1438 			com_loadchannelregs(sc);
1439 	}
1440 }
1441 
1442 void
1443 tiocm_to_com(struct com_softc *sc, u_long how, int ttybits)
1444 {
1445 	u_char combits;
1446 
1447 	combits = 0;
1448 	if (ISSET(ttybits, TIOCM_DTR))
1449 		SET(combits, MCR_DTR);
1450 	if (ISSET(ttybits, TIOCM_RTS))
1451 		SET(combits, MCR_RTS);
1452 
1453 	switch (how) {
1454 	case TIOCMBIC:
1455 		CLR(sc->sc_mcr, combits);
1456 		break;
1457 
1458 	case TIOCMBIS:
1459 		SET(sc->sc_mcr, combits);
1460 		break;
1461 
1462 	case TIOCMSET:
1463 		CLR(sc->sc_mcr, MCR_DTR | MCR_RTS);
1464 		SET(sc->sc_mcr, combits);
1465 		break;
1466 	}
1467 
1468 	if (!sc->sc_heldchange) {
1469 		if (sc->sc_tx_busy) {
1470 			sc->sc_heldtbc = sc->sc_tbc;
1471 			sc->sc_tbc = 0;
1472 			sc->sc_heldchange = 1;
1473 		} else
1474 			com_loadchannelregs(sc);
1475 	}
1476 }
1477 
1478 int
1479 com_to_tiocm(struct com_softc *sc)
1480 {
1481 	u_char combits;
1482 	int ttybits = 0;
1483 
1484 	combits = sc->sc_mcr;
1485 	if (ISSET(combits, MCR_DTR))
1486 		SET(ttybits, TIOCM_DTR);
1487 	if (ISSET(combits, MCR_RTS))
1488 		SET(ttybits, TIOCM_RTS);
1489 
1490 	combits = sc->sc_msr;
1491 	if (sc->sc_type == COM_TYPE_INGENIC) {
1492 		SET(ttybits, TIOCM_CD);
1493 	} else {
1494 		if (ISSET(combits, MSR_DCD))
1495 			SET(ttybits, TIOCM_CD);
1496 	}
1497 	if (ISSET(combits, MSR_CTS))
1498 		SET(ttybits, TIOCM_CTS);
1499 	if (ISSET(combits, MSR_DSR))
1500 		SET(ttybits, TIOCM_DSR);
1501 	if (ISSET(combits, MSR_RI | MSR_TERI))
1502 		SET(ttybits, TIOCM_RI);
1503 
1504 	if (ISSET(sc->sc_ier, IER_ERXRDY | IER_ETXRDY | IER_ERLS | IER_EMSC))
1505 		SET(ttybits, TIOCM_LE);
1506 
1507 	return (ttybits);
1508 }
1509 
1510 static u_char
1511 cflag2lcr(tcflag_t cflag)
1512 {
1513 	u_char lcr = 0;
1514 
1515 	switch (ISSET(cflag, CSIZE)) {
1516 	case CS5:
1517 		SET(lcr, LCR_5BITS);
1518 		break;
1519 	case CS6:
1520 		SET(lcr, LCR_6BITS);
1521 		break;
1522 	case CS7:
1523 		SET(lcr, LCR_7BITS);
1524 		break;
1525 	case CS8:
1526 		SET(lcr, LCR_8BITS);
1527 		break;
1528 	}
1529 	if (ISSET(cflag, PARENB)) {
1530 		SET(lcr, LCR_PENAB);
1531 		if (!ISSET(cflag, PARODD))
1532 			SET(lcr, LCR_PEVEN);
1533 	}
1534 	if (ISSET(cflag, CSTOPB))
1535 		SET(lcr, LCR_STOPB);
1536 
1537 	return (lcr);
1538 }
1539 
1540 int
1541 comparam(struct tty *tp, struct termios *t)
1542 {
1543 	struct com_softc *sc =
1544 	    device_lookup_private(&com_cd, COMUNIT(tp->t_dev));
1545 	int ospeed;
1546 	u_char lcr;
1547 
1548 	if (COM_ISALIVE(sc) == 0)
1549 		return (EIO);
1550 
1551 	if (sc->sc_type == COM_TYPE_HAYESP) {
1552 		int prescaler, speed;
1553 
1554 		/*
1555 		 * Calculate UART clock prescaler.  It should be in
1556 		 * range of 0 .. 3.
1557 		 */
1558 		for (prescaler = 0, speed = t->c_ospeed; prescaler < 4;
1559 		    prescaler++, speed /= 2)
1560 			if ((ospeed = comspeed(speed, sc->sc_frequency,
1561 					       sc->sc_type)) > 0)
1562 				break;
1563 
1564 		if (prescaler == 4)
1565 			return (EINVAL);
1566 		sc->sc_prescaler = prescaler;
1567 	} else
1568 		ospeed = comspeed(t->c_ospeed, sc->sc_frequency, sc->sc_type);
1569 
1570 	/* Check requested parameters. */
1571 	if (ospeed < 0)
1572 		return (EINVAL);
1573 	if (t->c_ispeed && t->c_ispeed != t->c_ospeed)
1574 		return (EINVAL);
1575 
1576 	/*
1577 	 * For the console, always force CLOCAL and !HUPCL, so that the port
1578 	 * is always active.
1579 	 */
1580 	if (ISSET(sc->sc_swflags, TIOCFLAG_SOFTCAR) ||
1581 	    ISSET(sc->sc_hwflags, COM_HW_CONSOLE)) {
1582 		SET(t->c_cflag, CLOCAL);
1583 		CLR(t->c_cflag, HUPCL);
1584 	}
1585 
1586 	/*
1587 	 * If there were no changes, don't do anything.  This avoids dropping
1588 	 * input and improves performance when all we did was frob things like
1589 	 * VMIN and VTIME.
1590 	 */
1591 	if (tp->t_ospeed == t->c_ospeed &&
1592 	    tp->t_cflag == t->c_cflag)
1593 		return (0);
1594 
1595 	lcr = ISSET(sc->sc_lcr, LCR_SBREAK) | cflag2lcr(t->c_cflag);
1596 
1597 	mutex_spin_enter(&sc->sc_lock);
1598 
1599 	sc->sc_lcr = lcr;
1600 
1601 	/*
1602 	 * If we're not in a mode that assumes a connection is present, then
1603 	 * ignore carrier changes.
1604 	 */
1605 	if (ISSET(t->c_cflag, CLOCAL | MDMBUF))
1606 		sc->sc_msr_dcd = 0;
1607 	else
1608 		sc->sc_msr_dcd = MSR_DCD;
1609 	/*
1610 	 * Set the flow control pins depending on the current flow control
1611 	 * mode.
1612 	 */
1613 	if (ISSET(t->c_cflag, CRTSCTS)) {
1614 		sc->sc_mcr_dtr = MCR_DTR;
1615 		sc->sc_mcr_rts = MCR_RTS;
1616 		sc->sc_msr_cts = MSR_CTS;
1617 		if (ISSET(sc->sc_hwflags, COM_HW_AFE)) {
1618 			SET(sc->sc_mcr, MCR_AFE);
1619 		} else {
1620 			sc->sc_efr = EFR_AUTORTS | EFR_AUTOCTS;
1621 		}
1622 	} else if (ISSET(t->c_cflag, MDMBUF)) {
1623 		/*
1624 		 * For DTR/DCD flow control, make sure we don't toggle DTR for
1625 		 * carrier detection.
1626 		 */
1627 		sc->sc_mcr_dtr = 0;
1628 		sc->sc_mcr_rts = MCR_DTR;
1629 		sc->sc_msr_cts = MSR_DCD;
1630 		if (ISSET(sc->sc_hwflags, COM_HW_AFE)) {
1631 			CLR(sc->sc_mcr, MCR_AFE);
1632 		} else {
1633 			sc->sc_efr = 0;
1634 		}
1635 	} else {
1636 		/*
1637 		 * If no flow control, then always set RTS.  This will make
1638 		 * the other side happy if it mistakenly thinks we're doing
1639 		 * RTS/CTS flow control.
1640 		 */
1641 		sc->sc_mcr_dtr = MCR_DTR | MCR_RTS;
1642 		sc->sc_mcr_rts = 0;
1643 		sc->sc_msr_cts = 0;
1644 		if (ISSET(sc->sc_hwflags, COM_HW_AFE)) {
1645 			CLR(sc->sc_mcr, MCR_AFE);
1646 		} else {
1647 			sc->sc_efr = 0;
1648 		}
1649 		if (ISSET(sc->sc_mcr, MCR_DTR))
1650 			SET(sc->sc_mcr, MCR_RTS);
1651 		else
1652 			CLR(sc->sc_mcr, MCR_RTS);
1653 	}
1654 	sc->sc_msr_mask = sc->sc_msr_cts | sc->sc_msr_dcd;
1655 
1656 	if (t->c_ospeed == 0 && tp->t_ospeed != 0)
1657 		CLR(sc->sc_mcr, sc->sc_mcr_dtr);
1658 	else if (t->c_ospeed != 0 && tp->t_ospeed == 0)
1659 		SET(sc->sc_mcr, sc->sc_mcr_dtr);
1660 
1661 	sc->sc_dlbl = ospeed;
1662 	sc->sc_dlbh = ospeed >> 8;
1663 
1664 	/*
1665 	 * Set the FIFO threshold based on the receive speed.
1666 	 *
1667 	 *  * If it's a low speed, it's probably a mouse or some other
1668 	 *    interactive device, so set the threshold low.
1669 	 *  * If it's a high speed, trim the trigger level down to prevent
1670 	 *    overflows.
1671 	 *  * Otherwise set it a bit higher.
1672 	 */
1673 	if (sc->sc_type == COM_TYPE_HAYESP) {
1674 		sc->sc_fifo = FIFO_DMA_MODE | FIFO_ENABLE | FIFO_TRIGGER_8;
1675 	} else if (sc->sc_type == COM_TYPE_TEGRA) {
1676 		sc->sc_fifo = FIFO_ENABLE | FIFO_TRIGGER_1;
1677 	} else if (ISSET(sc->sc_hwflags, COM_HW_FIFO)) {
1678 		if (t->c_ospeed <= 1200)
1679 			sc->sc_fifo = FIFO_ENABLE | FIFO_TRIGGER_1;
1680 		else if (t->c_ospeed <= 38400)
1681 			sc->sc_fifo = FIFO_ENABLE | FIFO_TRIGGER_8;
1682 		else
1683 			sc->sc_fifo = FIFO_ENABLE | FIFO_TRIGGER_4;
1684 	} else {
1685 		sc->sc_fifo = 0;
1686 	}
1687 
1688 	if (sc->sc_type == COM_TYPE_INGENIC)
1689 		sc->sc_fifo |= FIFO_UART_ON;
1690 
1691 	/* And copy to tty. */
1692 	tp->t_ispeed = t->c_ospeed;
1693 	tp->t_ospeed = t->c_ospeed;
1694 	tp->t_cflag = t->c_cflag;
1695 
1696 	if (!sc->sc_heldchange) {
1697 		if (sc->sc_tx_busy) {
1698 			sc->sc_heldtbc = sc->sc_tbc;
1699 			sc->sc_tbc = 0;
1700 			sc->sc_heldchange = 1;
1701 		} else
1702 			com_loadchannelregs(sc);
1703 	}
1704 
1705 	if (!ISSET(t->c_cflag, CHWFLOW)) {
1706 		/* Disable the high water mark. */
1707 		sc->sc_r_hiwat = 0;
1708 		sc->sc_r_lowat = 0;
1709 		if (ISSET(sc->sc_rx_flags, RX_TTY_OVERFLOWED)) {
1710 			CLR(sc->sc_rx_flags, RX_TTY_OVERFLOWED);
1711 			com_schedrx(sc);
1712 		}
1713 		if (ISSET(sc->sc_rx_flags, RX_TTY_BLOCKED|RX_IBUF_BLOCKED)) {
1714 			CLR(sc->sc_rx_flags, RX_TTY_BLOCKED|RX_IBUF_BLOCKED);
1715 			com_hwiflow(sc);
1716 		}
1717 	} else {
1718 		sc->sc_r_hiwat = com_rbuf_hiwat;
1719 		sc->sc_r_lowat = com_rbuf_lowat;
1720 	}
1721 
1722 	mutex_spin_exit(&sc->sc_lock);
1723 
1724 	/*
1725 	 * Update the tty layer's idea of the carrier bit, in case we changed
1726 	 * CLOCAL or MDMBUF.  We don't hang up here; we only do that by
1727 	 * explicit request.
1728 	 */
1729 	if (sc->sc_type == COM_TYPE_INGENIC) {
1730 		/* no DCD here */
1731 		(void) (*tp->t_linesw->l_modem)(tp, 1);
1732 	} else
1733 		(void) (*tp->t_linesw->l_modem)(tp, ISSET(sc->sc_msr, MSR_DCD));
1734 
1735 #ifdef COM_DEBUG
1736 	if (com_debug)
1737 		comstatus(sc, "comparam ");
1738 #endif
1739 
1740 	if (!ISSET(t->c_cflag, CHWFLOW)) {
1741 		if (sc->sc_tx_stopped) {
1742 			sc->sc_tx_stopped = 0;
1743 			comstart(tp);
1744 		}
1745 	}
1746 
1747 	return (0);
1748 }
1749 
1750 void
1751 com_iflush(struct com_softc *sc)
1752 {
1753 	struct com_regs	*regsp = &sc->sc_regs;
1754 	uint8_t fifo;
1755 #ifdef DIAGNOSTIC
1756 	int reg;
1757 #endif
1758 	int timo;
1759 
1760 #ifdef DIAGNOSTIC
1761 	reg = 0xffff;
1762 #endif
1763 	timo = 50000;
1764 	/* flush any pending I/O */
1765 	while (ISSET(CSR_READ_1(regsp, COM_REG_LSR), LSR_RXRDY)
1766 	    && --timo)
1767 #ifdef DIAGNOSTIC
1768 		reg =
1769 #else
1770 		    (void)
1771 #endif
1772 		    CSR_READ_1(regsp, COM_REG_RXDATA);
1773 #ifdef DIAGNOSTIC
1774 	if (!timo)
1775 		aprint_error_dev(sc->sc_dev, "com_iflush timeout %02x\n", reg);
1776 #endif
1777 
1778 	switch (sc->sc_type) {
1779 	case COM_TYPE_16750:
1780 	case COM_TYPE_DW_APB:
1781 		/*
1782 		 * Reset all Rx/Tx FIFO, preserve current FIFO length.
1783 		 * This should prevent triggering busy interrupt while
1784 		 * manipulating divisors.
1785 		 */
1786 		fifo = CSR_READ_1(regsp, COM_REG_FIFO) & (FIFO_TRIGGER_1 |
1787 		    FIFO_TRIGGER_4 | FIFO_TRIGGER_8 | FIFO_TRIGGER_14);
1788 		CSR_WRITE_1(regsp, COM_REG_FIFO,
1789 		    fifo | FIFO_ENABLE | FIFO_RCV_RST | FIFO_XMT_RST);
1790 		delay(100);
1791 		break;
1792 	}
1793 }
1794 
1795 void
1796 com_loadchannelregs(struct com_softc *sc)
1797 {
1798 	struct com_regs *regsp = &sc->sc_regs;
1799 
1800 	/* XXXXX necessary? */
1801 	com_iflush(sc);
1802 
1803 	if (sc->sc_type == COM_TYPE_PXA2x0)
1804 		CSR_WRITE_1(regsp, COM_REG_IER, IER_EUART);
1805 	else
1806 		CSR_WRITE_1(regsp, COM_REG_IER, 0);
1807 
1808 	if (sc->sc_type == COM_TYPE_OMAP) {
1809 		/* disable before changing settings */
1810 		CSR_WRITE_1(regsp, COM_REG_MDR1, MDR1_MODE_DISABLE);
1811 	}
1812 
1813 	if (ISSET(sc->sc_hwflags, COM_HW_FLOW)) {
1814 		KASSERT(sc->sc_type != COM_TYPE_AU1x00);
1815 		KASSERT(sc->sc_type != COM_TYPE_16550_NOERS);
1816 		/* no EFR on alchemy */
1817 		CSR_WRITE_1(regsp, COM_REG_LCR, LCR_EERS);
1818 		CSR_WRITE_1(regsp, COM_REG_EFR, sc->sc_efr);
1819 	}
1820 	if (sc->sc_type == COM_TYPE_AU1x00) {
1821 		/* alchemy has single separate 16-bit clock divisor register */
1822 		CSR_WRITE_2(regsp, COM_REG_DLBL, sc->sc_dlbl +
1823 		    (sc->sc_dlbh << 8));
1824 	} else {
1825 		CSR_WRITE_1(regsp, COM_REG_LCR, sc->sc_lcr | LCR_DLAB);
1826 		CSR_WRITE_1(regsp, COM_REG_DLBL, sc->sc_dlbl);
1827 		CSR_WRITE_1(regsp, COM_REG_DLBH, sc->sc_dlbh);
1828 	}
1829 	CSR_WRITE_1(regsp, COM_REG_LCR, sc->sc_lcr);
1830 	CSR_WRITE_1(regsp, COM_REG_MCR, sc->sc_mcr_active = sc->sc_mcr);
1831 	CSR_WRITE_1(regsp, COM_REG_FIFO, sc->sc_fifo);
1832 	if (sc->sc_type == COM_TYPE_HAYESP) {
1833 		bus_space_write_1(regsp->cr_iot, sc->sc_hayespioh, HAYESP_CMD1,
1834 		    HAYESP_SETPRESCALER);
1835 		bus_space_write_1(regsp->cr_iot, sc->sc_hayespioh, HAYESP_CMD2,
1836 		    sc->sc_prescaler);
1837 	}
1838 	if (sc->sc_type == COM_TYPE_OMAP) {
1839 		/* setup the fifos.  the FCR value is not used as long
1840 		   as SCR[6] and SCR[7] are 0, which they are at reset
1841 		   and we never touch the SCR register */
1842 		uint8_t rx_fifo_trig = 40;
1843 		uint8_t tx_fifo_trig = 60;
1844 		uint8_t rx_start = 8;
1845 		uint8_t rx_halt = 60;
1846 		uint8_t tlr_value = ((rx_fifo_trig>>2) << 4) | (tx_fifo_trig>>2);
1847 		uint8_t tcr_value = ((rx_start>>2) << 4) | (rx_halt>>2);
1848 
1849 		/* enable access to TCR & TLR */
1850 		CSR_WRITE_1(regsp, COM_REG_MCR, sc->sc_mcr | MCR_TCR_TLR);
1851 
1852 		/* write tcr and tlr values */
1853 		CSR_WRITE_1(regsp, COM_REG_TLR, tlr_value);
1854 		CSR_WRITE_1(regsp, COM_REG_TCR, tcr_value);
1855 
1856 		/* disable access to TCR & TLR */
1857 		CSR_WRITE_1(regsp, COM_REG_MCR, sc->sc_mcr);
1858 
1859 		/* enable again, but mode is based on speed */
1860 		if (sc->sc_tty->t_termios.c_ospeed > 230400) {
1861 			CSR_WRITE_1(regsp, COM_REG_MDR1, MDR1_MODE_UART_13X);
1862 		} else {
1863 			CSR_WRITE_1(regsp, COM_REG_MDR1, MDR1_MODE_UART_16X);
1864 		}
1865 	}
1866 
1867 	CSR_WRITE_1(regsp, COM_REG_IER, sc->sc_ier);
1868 }
1869 
1870 int
1871 comhwiflow(struct tty *tp, int block)
1872 {
1873 	struct com_softc *sc =
1874 	    device_lookup_private(&com_cd, COMUNIT(tp->t_dev));
1875 
1876 	if (COM_ISALIVE(sc) == 0)
1877 		return (0);
1878 
1879 	if (sc->sc_mcr_rts == 0)
1880 		return (0);
1881 
1882 	mutex_spin_enter(&sc->sc_lock);
1883 
1884 	if (block) {
1885 		if (!ISSET(sc->sc_rx_flags, RX_TTY_BLOCKED)) {
1886 			SET(sc->sc_rx_flags, RX_TTY_BLOCKED);
1887 			com_hwiflow(sc);
1888 		}
1889 	} else {
1890 		if (ISSET(sc->sc_rx_flags, RX_TTY_OVERFLOWED)) {
1891 			CLR(sc->sc_rx_flags, RX_TTY_OVERFLOWED);
1892 			com_schedrx(sc);
1893 		}
1894 		if (ISSET(sc->sc_rx_flags, RX_TTY_BLOCKED)) {
1895 			CLR(sc->sc_rx_flags, RX_TTY_BLOCKED);
1896 			com_hwiflow(sc);
1897 		}
1898 	}
1899 
1900 	mutex_spin_exit(&sc->sc_lock);
1901 	return (1);
1902 }
1903 
1904 /*
1905  * (un)block input via hw flowcontrol
1906  */
1907 void
1908 com_hwiflow(struct com_softc *sc)
1909 {
1910 	struct com_regs *regsp= &sc->sc_regs;
1911 
1912 	if (sc->sc_mcr_rts == 0)
1913 		return;
1914 
1915 	if (ISSET(sc->sc_rx_flags, RX_ANY_BLOCK)) {
1916 		CLR(sc->sc_mcr, sc->sc_mcr_rts);
1917 		CLR(sc->sc_mcr_active, sc->sc_mcr_rts);
1918 	} else {
1919 		SET(sc->sc_mcr, sc->sc_mcr_rts);
1920 		SET(sc->sc_mcr_active, sc->sc_mcr_rts);
1921 	}
1922 	CSR_WRITE_1(regsp, COM_REG_MCR, sc->sc_mcr_active);
1923 }
1924 
1925 
1926 void
1927 comstart(struct tty *tp)
1928 {
1929 	struct com_softc *sc =
1930 	    device_lookup_private(&com_cd, COMUNIT(tp->t_dev));
1931 	struct com_regs *regsp = &sc->sc_regs;
1932 
1933 	if (COM_ISALIVE(sc) == 0)
1934 		return;
1935 
1936 	if (ISSET(tp->t_state, TS_BUSY | TS_TIMEOUT | TS_TTSTOP))
1937 		return;
1938 	if (sc->sc_tx_stopped)
1939 		return;
1940 	if (!ttypull(tp))
1941 		return;
1942 
1943 	/* Grab the first contiguous region of buffer space. */
1944 	{
1945 		u_char *tba;
1946 		int tbc;
1947 
1948 		tba = tp->t_outq.c_cf;
1949 		tbc = ndqb(&tp->t_outq, 0);
1950 
1951 		mutex_spin_enter(&sc->sc_lock);
1952 
1953 		sc->sc_tba = tba;
1954 		sc->sc_tbc = tbc;
1955 	}
1956 
1957 	SET(tp->t_state, TS_BUSY);
1958 	sc->sc_tx_busy = 1;
1959 
1960 	/* Enable transmit completion interrupts if necessary. */
1961 	if (!ISSET(sc->sc_ier, IER_ETXRDY)) {
1962 		SET(sc->sc_ier, IER_ETXRDY);
1963 		CSR_WRITE_1(regsp, COM_REG_IER, sc->sc_ier);
1964 	}
1965 
1966 	/* Output the first chunk of the contiguous buffer. */
1967 	if (!ISSET(sc->sc_hwflags, COM_HW_NO_TXPRELOAD)) {
1968 		u_int n;
1969 
1970 		n = sc->sc_tbc;
1971 		if (n > sc->sc_fifolen)
1972 			n = sc->sc_fifolen;
1973 		CSR_WRITE_MULTI(regsp, COM_REG_TXDATA, sc->sc_tba, n);
1974 		sc->sc_tbc -= n;
1975 		sc->sc_tba += n;
1976 	}
1977 
1978 	mutex_spin_exit(&sc->sc_lock);
1979 }
1980 
1981 /*
1982  * Stop output on a line.
1983  */
1984 void
1985 comstop(struct tty *tp, int flag)
1986 {
1987 	struct com_softc *sc =
1988 	    device_lookup_private(&com_cd, COMUNIT(tp->t_dev));
1989 
1990 	mutex_spin_enter(&sc->sc_lock);
1991 	if (ISSET(tp->t_state, TS_BUSY)) {
1992 		/* Stop transmitting at the next chunk. */
1993 		sc->sc_tbc = 0;
1994 		sc->sc_heldtbc = 0;
1995 		if (!ISSET(tp->t_state, TS_TTSTOP))
1996 			SET(tp->t_state, TS_FLUSH);
1997 	}
1998 	mutex_spin_exit(&sc->sc_lock);
1999 }
2000 
2001 void
2002 comdiag(void *arg)
2003 {
2004 	struct com_softc *sc = arg;
2005 	int overflows, floods;
2006 
2007 	mutex_spin_enter(&sc->sc_lock);
2008 	overflows = sc->sc_overflows;
2009 	sc->sc_overflows = 0;
2010 	floods = sc->sc_floods;
2011 	sc->sc_floods = 0;
2012 	sc->sc_errors = 0;
2013 	mutex_spin_exit(&sc->sc_lock);
2014 
2015 	log(LOG_WARNING, "%s: %d silo overflow%s, %d ibuf flood%s\n",
2016 	    device_xname(sc->sc_dev),
2017 	    overflows, overflows == 1 ? "" : "s",
2018 	    floods, floods == 1 ? "" : "s");
2019 }
2020 
2021 static inline void
2022 com_rxsoft(struct com_softc *sc, struct tty *tp)
2023 {
2024 	int (*rint)(int, struct tty *) = tp->t_linesw->l_rint;
2025 	u_char *get, *end;
2026 	u_int cc, scc;
2027 	u_char lsr;
2028 	int code;
2029 
2030 	end = sc->sc_ebuf;
2031 	get = sc->sc_rbget;
2032 	scc = cc = com_rbuf_size - sc->sc_rbavail;
2033 
2034 	if (cc == com_rbuf_size) {
2035 		sc->sc_floods++;
2036 		if (sc->sc_errors++ == 0)
2037 			callout_reset(&sc->sc_diag_callout, 60 * hz,
2038 			    comdiag, sc);
2039 	}
2040 
2041 	/* If not yet open, drop the entire buffer content here */
2042 	if (!ISSET(tp->t_state, TS_ISOPEN)) {
2043 		get += cc << 1;
2044 		if (get >= end)
2045 			get -= com_rbuf_size << 1;
2046 		cc = 0;
2047 	}
2048 	while (cc) {
2049 		code = get[0];
2050 		lsr = get[1];
2051 		if (ISSET(lsr, LSR_OE | LSR_BI | LSR_FE | LSR_PE)) {
2052 			if (ISSET(lsr, LSR_OE)) {
2053 				sc->sc_overflows++;
2054 				if (sc->sc_errors++ == 0)
2055 					callout_reset(&sc->sc_diag_callout,
2056 					    60 * hz, comdiag, sc);
2057 			}
2058 			if (ISSET(lsr, LSR_BI | LSR_FE))
2059 				SET(code, TTY_FE);
2060 			if (ISSET(lsr, LSR_PE))
2061 				SET(code, TTY_PE);
2062 		}
2063 		if ((*rint)(code, tp) == -1) {
2064 			/*
2065 			 * The line discipline's buffer is out of space.
2066 			 */
2067 			if (!ISSET(sc->sc_rx_flags, RX_TTY_BLOCKED)) {
2068 				/*
2069 				 * We're either not using flow control, or the
2070 				 * line discipline didn't tell us to block for
2071 				 * some reason.  Either way, we have no way to
2072 				 * know when there's more space available, so
2073 				 * just drop the rest of the data.
2074 				 */
2075 				get += cc << 1;
2076 				if (get >= end)
2077 					get -= com_rbuf_size << 1;
2078 				cc = 0;
2079 			} else {
2080 				/*
2081 				 * Don't schedule any more receive processing
2082 				 * until the line discipline tells us there's
2083 				 * space available (through comhwiflow()).
2084 				 * Leave the rest of the data in the input
2085 				 * buffer.
2086 				 */
2087 				SET(sc->sc_rx_flags, RX_TTY_OVERFLOWED);
2088 			}
2089 			break;
2090 		}
2091 		get += 2;
2092 		if (get >= end)
2093 			get = sc->sc_rbuf;
2094 		cc--;
2095 	}
2096 
2097 	if (cc != scc) {
2098 		sc->sc_rbget = get;
2099 		mutex_spin_enter(&sc->sc_lock);
2100 
2101 		cc = sc->sc_rbavail += scc - cc;
2102 		/* Buffers should be ok again, release possible block. */
2103 		if (cc >= sc->sc_r_lowat) {
2104 			if (ISSET(sc->sc_rx_flags, RX_IBUF_OVERFLOWED)) {
2105 				CLR(sc->sc_rx_flags, RX_IBUF_OVERFLOWED);
2106 				SET(sc->sc_ier, IER_ERXRDY);
2107 				if (sc->sc_type == COM_TYPE_PXA2x0)
2108 					SET(sc->sc_ier, IER_ERXTOUT);
2109 				if (sc->sc_type == COM_TYPE_INGENIC ||
2110 				    sc->sc_type == COM_TYPE_TEGRA)
2111 					SET(sc->sc_ier, IER_ERXTOUT);
2112 
2113 				CSR_WRITE_1(&sc->sc_regs, COM_REG_IER,
2114 				    sc->sc_ier);
2115 			}
2116 			if (ISSET(sc->sc_rx_flags, RX_IBUF_BLOCKED)) {
2117 				CLR(sc->sc_rx_flags, RX_IBUF_BLOCKED);
2118 				com_hwiflow(sc);
2119 			}
2120 		}
2121 		mutex_spin_exit(&sc->sc_lock);
2122 	}
2123 }
2124 
2125 static inline void
2126 com_txsoft(struct com_softc *sc, struct tty *tp)
2127 {
2128 
2129 	CLR(tp->t_state, TS_BUSY);
2130 	if (ISSET(tp->t_state, TS_FLUSH))
2131 		CLR(tp->t_state, TS_FLUSH);
2132 	else
2133 		ndflush(&tp->t_outq, (int)(sc->sc_tba - tp->t_outq.c_cf));
2134 	(*tp->t_linesw->l_start)(tp);
2135 }
2136 
2137 static inline void
2138 com_stsoft(struct com_softc *sc, struct tty *tp)
2139 {
2140 	u_char msr, delta;
2141 
2142 	mutex_spin_enter(&sc->sc_lock);
2143 	msr = sc->sc_msr;
2144 	delta = sc->sc_msr_delta;
2145 	sc->sc_msr_delta = 0;
2146 	mutex_spin_exit(&sc->sc_lock);
2147 
2148 	if (ISSET(delta, sc->sc_msr_dcd)) {
2149 		/*
2150 		 * Inform the tty layer that carrier detect changed.
2151 		 */
2152 		(void) (*tp->t_linesw->l_modem)(tp, ISSET(msr, MSR_DCD));
2153 	}
2154 
2155 	if (ISSET(delta, sc->sc_msr_cts)) {
2156 		/* Block or unblock output according to flow control. */
2157 		if (ISSET(msr, sc->sc_msr_cts)) {
2158 			sc->sc_tx_stopped = 0;
2159 			(*tp->t_linesw->l_start)(tp);
2160 		} else {
2161 			sc->sc_tx_stopped = 1;
2162 		}
2163 	}
2164 
2165 #ifdef COM_DEBUG
2166 	if (com_debug)
2167 		comstatus(sc, "com_stsoft");
2168 #endif
2169 }
2170 
2171 void
2172 comsoft(void *arg)
2173 {
2174 	struct com_softc *sc = arg;
2175 	struct tty *tp;
2176 
2177 	if (COM_ISALIVE(sc) == 0)
2178 		return;
2179 
2180 	tp = sc->sc_tty;
2181 
2182 	if (sc->sc_rx_ready) {
2183 		sc->sc_rx_ready = 0;
2184 		com_rxsoft(sc, tp);
2185 	}
2186 
2187 	if (sc->sc_st_check) {
2188 		sc->sc_st_check = 0;
2189 		com_stsoft(sc, tp);
2190 	}
2191 
2192 	if (sc->sc_tx_done) {
2193 		sc->sc_tx_done = 0;
2194 		com_txsoft(sc, tp);
2195 	}
2196 }
2197 
2198 int
2199 comintr(void *arg)
2200 {
2201 	struct com_softc *sc = arg;
2202 	struct com_regs *regsp = &sc->sc_regs;
2203 
2204 	u_char *put, *end;
2205 	u_int cc;
2206 	u_char lsr, iir;
2207 
2208 	if (COM_ISALIVE(sc) == 0)
2209 		return (0);
2210 
2211 	KASSERT(regsp != NULL);
2212 
2213 	mutex_spin_enter(&sc->sc_lock);
2214 	iir = CSR_READ_1(regsp, COM_REG_IIR);
2215 
2216 	/* Handle ns16750-specific busy interrupt. */
2217 	if (sc->sc_type == COM_TYPE_16750 &&
2218 	    (iir & IIR_BUSY) == IIR_BUSY) {
2219 		for (int timeout = 10000;
2220 		    (CSR_READ_1(regsp, COM_REG_USR) & 0x1) != 0; timeout--)
2221 			if (timeout <= 0) {
2222 				aprint_error_dev(sc->sc_dev,
2223 				    "timeout while waiting for BUSY interrupt "
2224 				    "acknowledge\n");
2225 				mutex_spin_exit(&sc->sc_lock);
2226 				return (0);
2227 			}
2228 
2229 		CSR_WRITE_1(regsp, COM_REG_LCR, sc->sc_lcr);
2230 		iir = CSR_READ_1(regsp, COM_REG_IIR);
2231 	}
2232 
2233 	/* DesignWare APB UART BUSY interrupt */
2234 	if (sc->sc_type == COM_TYPE_DW_APB &&
2235 	    (iir & IIR_BUSY) == IIR_BUSY) {
2236 		if (ISSET(sc->sc_hwflags, COM_HW_CONSOLE)) {
2237 			(void)CSR_READ_1(regsp, COM_REG_USR);
2238 		} else if ((CSR_READ_1(regsp, COM_REG_USR) & 0x1) != 0) {
2239 			CSR_WRITE_1(regsp, COM_REG_HALT, HALT_CHCFG_EN);
2240 			CSR_WRITE_1(regsp, COM_REG_LCR, sc->sc_lcr | LCR_DLAB);
2241 			CSR_WRITE_1(regsp, COM_REG_DLBL, sc->sc_dlbl);
2242 			CSR_WRITE_1(regsp, COM_REG_DLBH, sc->sc_dlbh);
2243 			CSR_WRITE_1(regsp, COM_REG_LCR, sc->sc_lcr);
2244 			CSR_WRITE_1(regsp, COM_REG_HALT,
2245 			    HALT_CHCFG_EN | HALT_CHCFG_UD);
2246 			for (int timeout = 10000000;
2247 			    (CSR_READ_1(regsp, COM_REG_HALT) & HALT_CHCFG_UD) != 0;
2248 			    timeout--) {
2249 				if (timeout <= 0) {
2250 					aprint_error_dev(sc->sc_dev,
2251 					    "timeout while waiting for HALT "
2252 					    "update acknowledge 0x%x 0x%x\n",
2253 					    CSR_READ_1(regsp, COM_REG_HALT),
2254 					    CSR_READ_1(regsp, COM_REG_USR));
2255 					break;
2256 				}
2257 			}
2258 			CSR_WRITE_1(regsp, COM_REG_HALT, 0);
2259 			(void)CSR_READ_1(regsp, COM_REG_USR);
2260 		} else {
2261 			CSR_WRITE_1(regsp, COM_REG_LCR, sc->sc_lcr | LCR_DLAB);
2262 			CSR_WRITE_1(regsp, COM_REG_DLBL, sc->sc_dlbl);
2263 			CSR_WRITE_1(regsp, COM_REG_DLBH, sc->sc_dlbh);
2264 			CSR_WRITE_1(regsp, COM_REG_LCR, sc->sc_lcr);
2265 		}
2266 	}
2267 
2268 	end = sc->sc_ebuf;
2269 	put = sc->sc_rbput;
2270 	cc = sc->sc_rbavail;
2271 
2272 	if (ISSET(iir, IIR_NOPEND)) {
2273 		if (ISSET(sc->sc_hwflags, COM_HW_BROKEN_ETXRDY))
2274 			goto do_tx;
2275 		mutex_spin_exit(&sc->sc_lock);
2276 		return (0);
2277 	}
2278 
2279 again:	do {
2280 		u_char	msr, delta;
2281 
2282 		lsr = CSR_READ_1(regsp, COM_REG_LSR);
2283 		if (ISSET(lsr, LSR_BI)) {
2284 			int cn_trapped = 0; /* see above: cn_trap() */
2285 
2286 			cn_check_magic(sc->sc_tty->t_dev,
2287 				       CNC_BREAK, com_cnm_state);
2288 			if (cn_trapped)
2289 				continue;
2290 #if defined(KGDB) && !defined(DDB)
2291 			if (ISSET(sc->sc_hwflags, COM_HW_KGDB)) {
2292 				kgdb_connect(1);
2293 				continue;
2294 			}
2295 #endif
2296 		}
2297 
2298 		if (sc->sc_type == COM_TYPE_BCMAUXUART && ISSET(iir, IIR_RXRDY))
2299 			lsr |= LSR_RXRDY;
2300 
2301 		if (ISSET(lsr, LSR_RCV_MASK) &&
2302 		    !ISSET(sc->sc_rx_flags, RX_IBUF_OVERFLOWED)) {
2303 			while (cc > 0) {
2304 				int cn_trapped = 0;
2305 				put[0] = CSR_READ_1(regsp, COM_REG_RXDATA);
2306 				put[1] = lsr;
2307 				cn_check_magic(sc->sc_tty->t_dev,
2308 					       put[0], com_cnm_state);
2309 				if (cn_trapped)
2310 					goto next;
2311 				put += 2;
2312 				if (put >= end)
2313 					put = sc->sc_rbuf;
2314 				cc--;
2315 			next:
2316 				lsr = CSR_READ_1(regsp, COM_REG_LSR);
2317 				if (!ISSET(lsr, LSR_RCV_MASK))
2318 					break;
2319 			}
2320 
2321 			/*
2322 			 * Current string of incoming characters ended because
2323 			 * no more data was available or we ran out of space.
2324 			 * Schedule a receive event if any data was received.
2325 			 * If we're out of space, turn off receive interrupts.
2326 			 */
2327 			sc->sc_rbput = put;
2328 			sc->sc_rbavail = cc;
2329 			if (!ISSET(sc->sc_rx_flags, RX_TTY_OVERFLOWED))
2330 				sc->sc_rx_ready = 1;
2331 
2332 			/*
2333 			 * See if we are in danger of overflowing a buffer. If
2334 			 * so, use hardware flow control to ease the pressure.
2335 			 */
2336 			if (!ISSET(sc->sc_rx_flags, RX_IBUF_BLOCKED) &&
2337 			    cc < sc->sc_r_hiwat) {
2338 				SET(sc->sc_rx_flags, RX_IBUF_BLOCKED);
2339 				com_hwiflow(sc);
2340 			}
2341 
2342 			/*
2343 			 * If we're out of space, disable receive interrupts
2344 			 * until the queue has drained a bit.
2345 			 */
2346 			if (!cc) {
2347 				SET(sc->sc_rx_flags, RX_IBUF_OVERFLOWED);
2348 				switch (sc->sc_type) {
2349 				case COM_TYPE_PXA2x0:
2350 					CLR(sc->sc_ier, IER_ERXRDY|IER_ERXTOUT);
2351 					break;
2352 				case COM_TYPE_INGENIC:
2353 				case COM_TYPE_TEGRA:
2354 					CLR(sc->sc_ier,
2355 					    IER_ERXRDY | IER_ERXTOUT);
2356 					break;
2357 				default:
2358 					CLR(sc->sc_ier, IER_ERXRDY);
2359 					break;
2360 				}
2361 				CSR_WRITE_1(regsp, COM_REG_IER, sc->sc_ier);
2362 			}
2363 		} else {
2364 			if ((iir & (IIR_RXRDY|IIR_TXRDY)) == IIR_RXRDY) {
2365 				(void) CSR_READ_1(regsp, COM_REG_RXDATA);
2366 				continue;
2367 			}
2368 		}
2369 
2370 		msr = CSR_READ_1(regsp, COM_REG_MSR);
2371 		delta = msr ^ sc->sc_msr;
2372 		sc->sc_msr = msr;
2373 		if ((sc->sc_pps_state.ppsparam.mode & PPS_CAPTUREBOTH) &&
2374 		    (delta & MSR_DCD)) {
2375 			mutex_spin_enter(&timecounter_lock);
2376 			pps_capture(&sc->sc_pps_state);
2377 			pps_event(&sc->sc_pps_state,
2378 			    (msr & MSR_DCD) ?
2379 			    PPS_CAPTUREASSERT :
2380 			    PPS_CAPTURECLEAR);
2381 			mutex_spin_exit(&timecounter_lock);
2382 		}
2383 
2384 		/*
2385 		 * Process normal status changes
2386 		 */
2387 		if (ISSET(delta, sc->sc_msr_mask)) {
2388 			SET(sc->sc_msr_delta, delta);
2389 
2390 			/*
2391 			 * Stop output immediately if we lose the output
2392 			 * flow control signal or carrier detect.
2393 			 */
2394 			if (ISSET(~msr, sc->sc_msr_mask)) {
2395 				sc->sc_tbc = 0;
2396 				sc->sc_heldtbc = 0;
2397 #ifdef COM_DEBUG
2398 				if (com_debug)
2399 					comstatus(sc, "comintr  ");
2400 #endif
2401 			}
2402 
2403 			sc->sc_st_check = 1;
2404 		}
2405 	} while (!ISSET((iir =
2406 	    CSR_READ_1(regsp, COM_REG_IIR)), IIR_NOPEND) &&
2407 	    /*
2408 	     * Since some device (e.g., ST16C1550) doesn't clear IIR_TXRDY
2409 	     * by IIR read, so we can't do this way: `process all interrupts,
2410 	     * then do TX if possible'.
2411 	     */
2412 	    (iir & IIR_IMASK) != IIR_TXRDY);
2413 
2414 do_tx:
2415 	/*
2416 	 * Read LSR again, since there may be an interrupt between
2417 	 * the last LSR read and IIR read above.
2418 	 */
2419 	lsr = CSR_READ_1(regsp, COM_REG_LSR);
2420 
2421 	/*
2422 	 * See if data can be transmitted as well.
2423 	 * Schedule tx done event if no data left
2424 	 * and tty was marked busy.
2425 	 */
2426 	if (ISSET(lsr, LSR_TXRDY)) {
2427 		/*
2428 		 * If we've delayed a parameter change, do it now, and restart
2429 		 * output.
2430 		 */
2431 		if (sc->sc_heldchange) {
2432 			com_loadchannelregs(sc);
2433 			sc->sc_heldchange = 0;
2434 			sc->sc_tbc = sc->sc_heldtbc;
2435 			sc->sc_heldtbc = 0;
2436 		}
2437 
2438 		/* Output the next chunk of the contiguous buffer, if any. */
2439 		if (sc->sc_tbc > 0) {
2440 			u_int n;
2441 
2442 			n = sc->sc_tbc;
2443 			if (n > sc->sc_fifolen)
2444 				n = sc->sc_fifolen;
2445 			CSR_WRITE_MULTI(regsp, COM_REG_TXDATA, sc->sc_tba, n);
2446 			sc->sc_tbc -= n;
2447 			sc->sc_tba += n;
2448 		} else {
2449 			/* Disable transmit completion interrupts if necessary. */
2450 			if (ISSET(sc->sc_ier, IER_ETXRDY)) {
2451 				CLR(sc->sc_ier, IER_ETXRDY);
2452 				CSR_WRITE_1(regsp, COM_REG_IER, sc->sc_ier);
2453 			}
2454 			if (sc->sc_tx_busy) {
2455 				sc->sc_tx_busy = 0;
2456 				sc->sc_tx_done = 1;
2457 			}
2458 		}
2459 	}
2460 
2461 	if (!ISSET((iir = CSR_READ_1(regsp, COM_REG_IIR)), IIR_NOPEND))
2462 		goto again;
2463 
2464 	mutex_spin_exit(&sc->sc_lock);
2465 
2466 	/* Wake up the poller. */
2467 	if ((sc->sc_rx_ready | sc->sc_st_check | sc->sc_tx_done) != 0)
2468 		softint_schedule(sc->sc_si);
2469 
2470 #ifdef RND_COM
2471 	rnd_add_uint32(&sc->rnd_source, iir | lsr);
2472 #endif
2473 
2474 	return (1);
2475 }
2476 
2477 /*
2478  * The following functions are polled getc and putc routines, shared
2479  * by the console and kgdb glue.
2480  *
2481  * The read-ahead code is so that you can detect pending in-band
2482  * cn_magic in polled mode while doing output rather than having to
2483  * wait until the kernel decides it needs input.
2484  */
2485 
2486 #define MAX_READAHEAD	20
2487 static int com_readahead[MAX_READAHEAD];
2488 static int com_readaheadcount = 0;
2489 
2490 int
2491 com_common_getc(dev_t dev, struct com_regs *regsp)
2492 {
2493 	int s = splserial();
2494 	u_char stat, c;
2495 
2496 	/* got a character from reading things earlier */
2497 	if (com_readaheadcount > 0) {
2498 		int i;
2499 
2500 		c = com_readahead[0];
2501 		for (i = 1; i < com_readaheadcount; i++) {
2502 			com_readahead[i-1] = com_readahead[i];
2503 		}
2504 		com_readaheadcount--;
2505 		splx(s);
2506 		return (c);
2507 	}
2508 
2509 	/* don't block until a character becomes available */
2510 	if (!ISSET(stat = CSR_READ_1(regsp, COM_REG_LSR), LSR_RXRDY)) {
2511 		splx(s);
2512 		return -1;
2513 	}
2514 
2515 	c = CSR_READ_1(regsp, COM_REG_RXDATA);
2516 	stat = CSR_READ_1(regsp, COM_REG_IIR);
2517 	{
2518 		int cn_trapped = 0;	/* required by cn_trap, see above */
2519 #ifdef DDB
2520 		extern int db_active;
2521 		if (!db_active)
2522 #endif
2523 			cn_check_magic(dev, c, com_cnm_state);
2524 	}
2525 	splx(s);
2526 	return (c);
2527 }
2528 
2529 static void
2530 com_common_putc(dev_t dev, struct com_regs *regsp, int c, int with_readahead)
2531 {
2532 	int s = splserial();
2533 	int cin, stat, timo;
2534 
2535 	if (with_readahead && com_readaheadcount < MAX_READAHEAD
2536 	     && ISSET(stat = CSR_READ_1(regsp, COM_REG_LSR), LSR_RXRDY)) {
2537 		int cn_trapped = 0;
2538 		cin = CSR_READ_1(regsp, COM_REG_RXDATA);
2539 		stat = CSR_READ_1(regsp, COM_REG_IIR);
2540 		cn_check_magic(dev, cin, com_cnm_state);
2541 		com_readahead[com_readaheadcount++] = cin;
2542 	}
2543 
2544 	/* wait for any pending transmission to finish */
2545 	timo = 150000;
2546 	while (!ISSET(CSR_READ_1(regsp, COM_REG_LSR), LSR_TXRDY) && --timo)
2547 		continue;
2548 
2549 	CSR_WRITE_1(regsp, COM_REG_TXDATA, c);
2550 	COM_BARRIER(regsp, BR | BW);
2551 
2552 	splx(s);
2553 }
2554 
2555 /*
2556  * Initialize UART for use as console or KGDB line.
2557  */
2558 int
2559 cominit(struct com_regs *regsp, int rate, int frequency, int type,
2560     tcflag_t cflag)
2561 {
2562 
2563 	if (bus_space_map(regsp->cr_iot, regsp->cr_iobase, regsp->cr_nports, 0,
2564 		&regsp->cr_ioh))
2565 		return (ENOMEM); /* ??? */
2566 
2567 	if (type == COM_TYPE_OMAP) {
2568 		/* disable before changing settings */
2569 		CSR_WRITE_1(regsp, COM_REG_MDR1, MDR1_MODE_DISABLE);
2570 	}
2571 
2572 	rate = comspeed(rate, frequency, type);
2573 	if (rate != -1) {
2574 		if (type == COM_TYPE_AU1x00) {
2575 			/* no EFR on alchemy */
2576 			CSR_WRITE_2(regsp, COM_REG_DLBL, rate);
2577 		} else {
2578 			if ((type != COM_TYPE_16550_NOERS) &&
2579 			    (type != COM_TYPE_INGENIC)) {
2580 				CSR_WRITE_1(regsp, COM_REG_LCR, LCR_EERS);
2581 				CSR_WRITE_1(regsp, COM_REG_EFR, 0);
2582 			}
2583 			CSR_WRITE_1(regsp, COM_REG_LCR, LCR_DLAB);
2584 			CSR_WRITE_1(regsp, COM_REG_DLBL, rate & 0xff);
2585 			CSR_WRITE_1(regsp, COM_REG_DLBH, rate >> 8);
2586 		}
2587 	}
2588 	CSR_WRITE_1(regsp, COM_REG_LCR, cflag2lcr(cflag));
2589 	CSR_WRITE_1(regsp, COM_REG_MCR, MCR_DTR | MCR_RTS);
2590 
2591 	if (type == COM_TYPE_INGENIC) {
2592 		CSR_WRITE_1(regsp, COM_REG_FIFO,
2593 		    FIFO_ENABLE | FIFO_RCV_RST | FIFO_XMT_RST |
2594 		    FIFO_TRIGGER_1 | FIFO_UART_ON);
2595 	} else {
2596 		CSR_WRITE_1(regsp, COM_REG_FIFO,
2597 		    FIFO_ENABLE | FIFO_RCV_RST | FIFO_XMT_RST |
2598 		    FIFO_TRIGGER_1);
2599 	}
2600 
2601 	if (type == COM_TYPE_OMAP) {
2602 		/* setup the fifos.  the FCR value is not used as long
2603 		   as SCR[6] and SCR[7] are 0, which they are at reset
2604 		   and we never touch the SCR register */
2605 		uint8_t rx_fifo_trig = 40;
2606 		uint8_t tx_fifo_trig = 60;
2607 		uint8_t rx_start = 8;
2608 		uint8_t rx_halt = 60;
2609 		uint8_t tlr_value = ((rx_fifo_trig>>2) << 4) | (tx_fifo_trig>>2);
2610 		uint8_t tcr_value = ((rx_start>>2) << 4) | (rx_halt>>2);
2611 
2612 		/* enable access to TCR & TLR */
2613 		CSR_WRITE_1(regsp, COM_REG_MCR, MCR_DTR | MCR_RTS | MCR_TCR_TLR);
2614 
2615 		/* write tcr and tlr values */
2616 		CSR_WRITE_1(regsp, COM_REG_TLR, tlr_value);
2617 		CSR_WRITE_1(regsp, COM_REG_TCR, tcr_value);
2618 
2619 		/* disable access to TCR & TLR */
2620 		CSR_WRITE_1(regsp, COM_REG_MCR, MCR_DTR | MCR_RTS);
2621 
2622 		/* enable again, but mode is based on speed */
2623 		if (rate > 230400) {
2624 			CSR_WRITE_1(regsp, COM_REG_MDR1, MDR1_MODE_UART_13X);
2625 		} else {
2626 			CSR_WRITE_1(regsp, COM_REG_MDR1, MDR1_MODE_UART_16X);
2627 		}
2628 	}
2629 
2630 	if (type == COM_TYPE_PXA2x0)
2631 		CSR_WRITE_1(regsp, COM_REG_IER, IER_EUART);
2632 	else
2633 		CSR_WRITE_1(regsp, COM_REG_IER, 0);
2634 
2635 	return (0);
2636 }
2637 
2638 int
2639 comcnattach1(struct com_regs *regsp, int rate, int frequency, int type,
2640     tcflag_t cflag)
2641 {
2642 	int res;
2643 
2644 	comcons_info.regs = *regsp;
2645 
2646 	res = cominit(&comcons_info.regs, rate, frequency, type, cflag);
2647 	if (res)
2648 		return (res);
2649 
2650 	cn_tab = &comcons;
2651 	cn_init_magic(&com_cnm_state);
2652 	cn_set_magic("\047\001"); /* default magic is BREAK */
2653 
2654 	comcons_info.frequency = frequency;
2655 	comcons_info.type = type;
2656 	comcons_info.rate = rate;
2657 	comcons_info.cflag = cflag;
2658 
2659 	return (0);
2660 }
2661 
2662 int
2663 comcnattach(bus_space_tag_t iot, bus_addr_t iobase, int rate, int frequency,
2664     int type, tcflag_t cflag)
2665 {
2666 	struct com_regs	regs;
2667 
2668 	/*XXX*/
2669 	bus_space_handle_t dummy_bsh;
2670 	memset(&dummy_bsh, 0, sizeof(dummy_bsh));
2671 
2672 	/*
2673 	 * dummy_bsh required because com_init_regs() wants it.  A
2674 	 * real bus_space_handle will be filled in by cominit() later.
2675 	 * XXXJRT Detangle this mess eventually, plz.
2676 	 */
2677 	com_init_regs(&regs, iot, dummy_bsh/*XXX*/, iobase);
2678 
2679 	return comcnattach1(&regs, rate, frequency, type, cflag);
2680 }
2681 
2682 static int
2683 comcnreattach(void)
2684 {
2685 	return comcnattach1(&comcons_info.regs, comcons_info.rate,
2686 	    comcons_info.frequency, comcons_info.type, comcons_info.cflag);
2687 }
2688 
2689 int
2690 comcngetc(dev_t dev)
2691 {
2692 
2693 	return (com_common_getc(dev, &comcons_info.regs));
2694 }
2695 
2696 /*
2697  * Console kernel output character routine.
2698  */
2699 void
2700 comcnputc(dev_t dev, int c)
2701 {
2702 
2703 	com_common_putc(dev, &comcons_info.regs, c, cold);
2704 }
2705 
2706 void
2707 comcnpollc(dev_t dev, int on)
2708 {
2709 
2710 	com_readaheadcount = 0;
2711 }
2712 
2713 #ifdef KGDB
2714 int
2715 com_kgdb_attach1(struct com_regs *regsp, int rate, int frequency, int type,
2716     tcflag_t cflag)
2717 {
2718 	int res;
2719 
2720 	if (bus_space_is_equal(regsp->cr_iot, comcons_info.regs.cr_iot) &&
2721 	    regsp->cr_iobase == comcons_info.regs.cr_iobase) {
2722 #if !defined(DDB)
2723 		return (EBUSY); /* cannot share with console */
2724 #else
2725 		comkgdbregs = *regsp;
2726 		comkgdbregs.cr_ioh = comcons_info.regs.cr_ioh;
2727 #endif
2728 	} else {
2729 		comkgdbregs = *regsp;
2730 		res = cominit(&comkgdbregs, rate, frequency, type, cflag);
2731 		if (res)
2732 			return (res);
2733 
2734 		/*
2735 		 * XXXfvdl this shouldn't be needed, but the cn_magic goo
2736 		 * expects this to be initialized
2737 		 */
2738 		cn_init_magic(&com_cnm_state);
2739 		cn_set_magic("\047\001");
2740 	}
2741 
2742 	kgdb_attach(com_kgdb_getc, com_kgdb_putc, NULL);
2743 	kgdb_dev = 123; /* unneeded, only to satisfy some tests */
2744 
2745 	return (0);
2746 }
2747 
2748 int
2749 com_kgdb_attach(bus_space_tag_t iot, bus_addr_t iobase, int rate,
2750     int frequency, int type, tcflag_t cflag)
2751 {
2752 	struct com_regs regs;
2753 
2754 	com_init_regs(&regs, iot, (bus_space_handle_t)0/*XXX*/, iobase);
2755 
2756 	return com_kgdb_attach1(&regs, rate, frequency, type, cflag);
2757 }
2758 
2759 /* ARGSUSED */
2760 int
2761 com_kgdb_getc(void *arg)
2762 {
2763 
2764 	return (com_common_getc(NODEV, &comkgdbregs));
2765 }
2766 
2767 /* ARGSUSED */
2768 void
2769 com_kgdb_putc(void *arg, int c)
2770 {
2771 
2772 	com_common_putc(NODEV, &comkgdbregs, c, 0);
2773 }
2774 #endif /* KGDB */
2775 
2776 /* helper function to identify the com ports used by
2777  console or KGDB (and not yet autoconf attached) */
2778 int
2779 com_is_console(bus_space_tag_t iot, bus_addr_t iobase, bus_space_handle_t *ioh)
2780 {
2781 	bus_space_handle_t help;
2782 
2783 	if (!comconsattached &&
2784 	    bus_space_is_equal(iot, comcons_info.regs.cr_iot) &&
2785 	    iobase == comcons_info.regs.cr_iobase)
2786 		help = comcons_info.regs.cr_ioh;
2787 #ifdef KGDB
2788 	else if (!com_kgdb_attached &&
2789 	    bus_space_is_equal(iot, comkgdbregs.cr_iot) &&
2790 	    iobase == comkgdbregs.cr_iobase)
2791 		help = comkgdbregs.cr_ioh;
2792 #endif
2793 	else
2794 		return (0);
2795 
2796 	if (ioh)
2797 		*ioh = help;
2798 	return (1);
2799 }
2800 
2801 /*
2802  * this routine exists to serve as a shutdown hook for systems that
2803  * have firmware which doesn't interact properly with a com device in
2804  * FIFO mode.
2805  */
2806 bool
2807 com_cleanup(device_t self, int how)
2808 {
2809 	struct com_softc *sc = device_private(self);
2810 
2811 	if (ISSET(sc->sc_hwflags, COM_HW_FIFO))
2812 		CSR_WRITE_1(&sc->sc_regs, COM_REG_FIFO, 0);
2813 
2814 	return true;
2815 }
2816 
2817 bool
2818 com_suspend(device_t self, const pmf_qual_t *qual)
2819 {
2820 	struct com_softc *sc = device_private(self);
2821 
2822 	CSR_WRITE_1(&sc->sc_regs, COM_REG_IER, 0);
2823 	(void)CSR_READ_1(&sc->sc_regs, COM_REG_IIR);
2824 
2825 	return true;
2826 }
2827 
2828 bool
2829 com_resume(device_t self, const pmf_qual_t *qual)
2830 {
2831 	struct com_softc *sc = device_private(self);
2832 
2833 	mutex_spin_enter(&sc->sc_lock);
2834 	com_loadchannelregs(sc);
2835 	mutex_spin_exit(&sc->sc_lock);
2836 
2837 	return true;
2838 }
2839