xref: /freebsd/sys/dev/uart/uart_core.c (revision 45dd2eaac379e5576f745380260470204c49beac)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2003 Marcel Moolenaar
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
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  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/bus.h>
35 #include <sys/conf.h>
36 #include <sys/cons.h>
37 #include <sys/fcntl.h>
38 #include <sys/interrupt.h>
39 #include <sys/kdb.h>
40 #include <sys/kernel.h>
41 #include <sys/malloc.h>
42 #include <sys/queue.h>
43 #include <sys/reboot.h>
44 #include <sys/sysctl.h>
45 #include <machine/bus.h>
46 #include <sys/rman.h>
47 #include <machine/resource.h>
48 #include <machine/stdarg.h>
49 
50 #include <dev/uart/uart.h>
51 #include <dev/uart/uart_bus.h>
52 #include <dev/uart/uart_cpu.h>
53 #include <dev/uart/uart_ppstypes.h>
54 
55 #include "uart_if.h"
56 
57 devclass_t uart_devclass;
58 const char uart_driver_name[] = "uart";
59 
60 SLIST_HEAD(uart_devinfo_list, uart_devinfo) uart_sysdevs =
61     SLIST_HEAD_INITIALIZER(uart_sysdevs);
62 
63 static MALLOC_DEFINE(M_UART, "UART", "UART driver");
64 
65 #ifndef	UART_POLL_FREQ
66 #define	UART_POLL_FREQ		50
67 #endif
68 static int uart_poll_freq = UART_POLL_FREQ;
69 SYSCTL_INT(_debug, OID_AUTO, uart_poll_freq, CTLFLAG_RDTUN, &uart_poll_freq,
70     0, "UART poll frequency");
71 
72 static int uart_force_poll;
73 SYSCTL_INT(_debug, OID_AUTO, uart_force_poll, CTLFLAG_RDTUN, &uart_force_poll,
74     0, "Force UART polling");
75 
76 static inline int
77 uart_pps_mode_valid(int pps_mode)
78 {
79 	int opt;
80 
81 	switch(pps_mode & UART_PPS_SIGNAL_MASK) {
82 	case UART_PPS_DISABLED:
83 	case UART_PPS_CTS:
84 	case UART_PPS_DCD:
85 		break;
86 	default:
87 		return (false);
88 	}
89 
90 	opt = pps_mode & UART_PPS_OPTION_MASK;
91 	if ((opt & ~(UART_PPS_INVERT_PULSE | UART_PPS_NARROW_PULSE)) != 0)
92 		return (false);
93 
94 	return (true);
95 }
96 
97 static void
98 uart_pps_print_mode(struct uart_softc *sc)
99 {
100 
101 	device_printf(sc->sc_dev, "PPS capture mode: ");
102 	switch(sc->sc_pps_mode & UART_PPS_SIGNAL_MASK) {
103 	case UART_PPS_DISABLED:
104 		printf("disabled");
105 		break;
106 	case UART_PPS_CTS:
107 		printf("CTS");
108 		break;
109 	case UART_PPS_DCD:
110 		printf("DCD");
111 		break;
112 	default:
113 		printf("invalid");
114 		break;
115 	}
116 	if (sc->sc_pps_mode & UART_PPS_INVERT_PULSE)
117 		printf("-Inverted");
118 	if (sc->sc_pps_mode & UART_PPS_NARROW_PULSE)
119 		printf("-NarrowPulse");
120 	printf("\n");
121 }
122 
123 static int
124 uart_pps_mode_sysctl(SYSCTL_HANDLER_ARGS)
125 {
126 	struct uart_softc *sc;
127 	int err, tmp;
128 
129 	sc = arg1;
130 	tmp = sc->sc_pps_mode;
131 	err = sysctl_handle_int(oidp, &tmp, 0, req);
132 	if (err != 0 || req->newptr == NULL)
133 		return (err);
134 	if (!uart_pps_mode_valid(tmp))
135 		return (EINVAL);
136 	sc->sc_pps_mode = tmp;
137 	return(0);
138 }
139 
140 static void
141 uart_pps_process(struct uart_softc *sc, int ser_sig)
142 {
143 	sbintime_t now;
144 	int is_assert, pps_sig;
145 
146 	/* Which signal is configured as PPS?  Early out if none. */
147 	switch(sc->sc_pps_mode & UART_PPS_SIGNAL_MASK) {
148 	case UART_PPS_CTS:
149 		pps_sig = SER_CTS;
150 		break;
151 	case UART_PPS_DCD:
152 		pps_sig = SER_DCD;
153 		break;
154 	default:
155 		return;
156 	}
157 
158 	/* Early out if there is no change in the signal configured as PPS. */
159 	if ((ser_sig & SER_DELTA(pps_sig)) == 0)
160 		return;
161 
162 	/*
163 	 * In narrow-pulse mode we need to synthesize both capture and clear
164 	 * events from a single "delta occurred" indication from the uart
165 	 * hardware because the pulse width is too narrow to reliably detect
166 	 * both edges.  However, when the pulse width is close to our interrupt
167 	 * processing latency we might intermittantly catch both edges.  To
168 	 * guard against generating spurious events when that happens, we use a
169 	 * separate timer to ensure at least half a second elapses before we
170 	 * generate another event.
171 	 */
172 	pps_capture(&sc->sc_pps);
173 	if (sc->sc_pps_mode & UART_PPS_NARROW_PULSE) {
174 		now = getsbinuptime();
175 		if (now > sc->sc_pps_captime + 500 * SBT_1MS) {
176 			sc->sc_pps_captime = now;
177 			pps_event(&sc->sc_pps, PPS_CAPTUREASSERT);
178 			pps_event(&sc->sc_pps, PPS_CAPTURECLEAR);
179 		}
180 	} else  {
181 		is_assert = ser_sig & pps_sig;
182 		if (sc->sc_pps_mode & UART_PPS_INVERT_PULSE)
183 			is_assert = !is_assert;
184 		pps_event(&sc->sc_pps, is_assert ? PPS_CAPTUREASSERT :
185 		    PPS_CAPTURECLEAR);
186 	}
187 }
188 
189 static void
190 uart_pps_init(struct uart_softc *sc)
191 {
192 	struct sysctl_ctx_list *ctx;
193 	struct sysctl_oid *tree;
194 
195 	ctx = device_get_sysctl_ctx(sc->sc_dev);
196 	tree = device_get_sysctl_tree(sc->sc_dev);
197 
198 	/*
199 	 * The historical default for pps capture mode is either DCD or CTS,
200 	 * depending on the UART_PPS_ON_CTS kernel option.  Start with that,
201 	 * then try to fetch the tunable that overrides the mode for all uart
202 	 * devices, then try to fetch the sysctl-tunable that overrides the mode
203 	 * for one specific device.
204 	 */
205 #ifdef UART_PPS_ON_CTS
206 	sc->sc_pps_mode = UART_PPS_CTS;
207 #else
208 	sc->sc_pps_mode = UART_PPS_DCD;
209 #endif
210 	TUNABLE_INT_FETCH("hw.uart.pps_mode", &sc->sc_pps_mode);
211 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "pps_mode",
212 	    CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE, sc, 0,
213 	    uart_pps_mode_sysctl, "I", "pulse mode: 0/1/2=disabled/CTS/DCD; "
214 	    "add 0x10 to invert, 0x20 for narrow pulse");
215 
216 	if (!uart_pps_mode_valid(sc->sc_pps_mode)) {
217 		device_printf(sc->sc_dev,
218 		    "Invalid pps_mode 0x%02x configured; disabling PPS capture\n",
219 		    sc->sc_pps_mode);
220 		sc->sc_pps_mode = UART_PPS_DISABLED;
221 	} else if (bootverbose) {
222 		uart_pps_print_mode(sc);
223 	}
224 
225 	sc->sc_pps.ppscap = PPS_CAPTUREBOTH;
226 	sc->sc_pps.driver_mtx = uart_tty_getlock(sc);
227 	sc->sc_pps.driver_abi = PPS_ABI_VERSION;
228 	pps_init_abi(&sc->sc_pps);
229 }
230 
231 void
232 uart_add_sysdev(struct uart_devinfo *di)
233 {
234 	SLIST_INSERT_HEAD(&uart_sysdevs, di, next);
235 }
236 
237 const char *
238 uart_getname(struct uart_class *uc)
239 {
240 	return ((uc != NULL) ? uc->name : NULL);
241 }
242 
243 struct uart_ops *
244 uart_getops(struct uart_class *uc)
245 {
246 	return ((uc != NULL) ? uc->uc_ops : NULL);
247 }
248 
249 int
250 uart_getrange(struct uart_class *uc)
251 {
252 	return ((uc != NULL) ? uc->uc_range : 0);
253 }
254 
255 u_int
256 uart_getregshift(struct uart_class *uc)
257 {
258 	return ((uc != NULL) ? uc->uc_rshift : 0);
259 }
260 
261 u_int
262 uart_getregiowidth(struct uart_class *uc)
263 {
264 	return ((uc != NULL) ? uc->uc_riowidth : 0);
265 }
266 
267 /*
268  * Schedule a soft interrupt. We do this on the 0 to !0 transition
269  * of the TTY pending interrupt status.
270  */
271 void
272 uart_sched_softih(struct uart_softc *sc, uint32_t ipend)
273 {
274 	uint32_t new, old;
275 
276 	do {
277 		old = sc->sc_ttypend;
278 		new = old | ipend;
279 	} while (!atomic_cmpset_32(&sc->sc_ttypend, old, new));
280 
281 	if ((old & SER_INT_MASK) == 0)
282 		swi_sched(sc->sc_softih, 0);
283 }
284 
285 /*
286  * A break condition has been detected. We treat the break condition as
287  * a special case that should not happen during normal operation. When
288  * the break condition is to be passed to higher levels in the form of
289  * a NUL character, we really want the break to be in the right place in
290  * the input stream. The overhead to achieve that is not in relation to
291  * the exceptional nature of the break condition, so we permit ourselves
292  * to be sloppy.
293  */
294 static __inline int
295 uart_intr_break(void *arg)
296 {
297 	struct uart_softc *sc = arg;
298 
299 #if defined(KDB)
300 	if (sc->sc_sysdev != NULL && sc->sc_sysdev->type == UART_DEV_CONSOLE) {
301 		if (kdb_break())
302 			return (0);
303 	}
304 #endif
305 	if (sc->sc_opened)
306 		uart_sched_softih(sc, SER_INT_BREAK);
307 	return (0);
308 }
309 
310 /*
311  * Handle a receiver overrun situation. We lost at least 1 byte in the
312  * input stream and it's our job to contain the situation. We grab as
313  * much of the data we can, but otherwise flush the receiver FIFO to
314  * create some breathing room. The net effect is that we avoid the
315  * overrun condition to happen for the next X characters, where X is
316  * related to the FIFO size at the cost of losing data right away.
317  * So, instead of having multiple overrun interrupts in close proximity
318  * to each other and possibly pessimizing UART interrupt latency for
319  * other UARTs in a multiport configuration, we create a longer segment
320  * of missing characters by freeing up the FIFO.
321  * Each overrun condition is marked in the input buffer by a token. The
322  * token represents the loss of at least one, but possible more bytes in
323  * the input stream.
324  */
325 static __inline int
326 uart_intr_overrun(void *arg)
327 {
328 	struct uart_softc *sc = arg;
329 
330 	if (sc->sc_opened) {
331 		UART_RECEIVE(sc);
332 		if (uart_rx_put(sc, UART_STAT_OVERRUN))
333 			sc->sc_rxbuf[sc->sc_rxput] = UART_STAT_OVERRUN;
334 		uart_sched_softih(sc, SER_INT_RXREADY);
335 	}
336 	sc->sc_rxoverruns++;
337 	UART_FLUSH(sc, UART_FLUSH_RECEIVER);
338 	return (0);
339 }
340 
341 /*
342  * Received data ready.
343  */
344 static __inline int
345 uart_intr_rxready(void *arg)
346 {
347 	struct uart_softc *sc = arg;
348 #if defined(KDB)
349 	int rxp;
350 
351 	rxp = sc->sc_rxput;
352 #endif
353 	UART_RECEIVE(sc);
354 #if defined(KDB)
355 	if (sc->sc_sysdev != NULL && sc->sc_sysdev->type == UART_DEV_CONSOLE) {
356 		while (rxp != sc->sc_rxput) {
357 			kdb_alt_break(sc->sc_rxbuf[rxp++], &sc->sc_altbrk);
358 			if (rxp == sc->sc_rxbufsz)
359 				rxp = 0;
360 		}
361 	}
362 #endif
363 	if (sc->sc_opened)
364 		uart_sched_softih(sc, SER_INT_RXREADY);
365 	else
366 		sc->sc_rxput = sc->sc_rxget;	/* Ignore received data. */
367 	return (1);
368 }
369 
370 /*
371  * Line or modem status change (OOB signalling).
372  * We pass the signals to the software interrupt handler for further
373  * processing. Note that we merge the delta bits, but set the state
374  * bits. This is to avoid losing state transitions due to having more
375  * than 1 hardware interrupt between software interrupts.
376  */
377 static __inline int
378 uart_intr_sigchg(void *arg)
379 {
380 	struct uart_softc *sc = arg;
381 	int new, old, sig;
382 
383 	sig = UART_GETSIG(sc);
384 
385 	/*
386 	 * Time pulse counting support, invoked whenever the PPS parameters are
387 	 * currently set to capture either edge of the signal.
388 	 */
389 	if (sc->sc_pps.ppsparam.mode & PPS_CAPTUREBOTH) {
390 		uart_pps_process(sc, sig);
391 	}
392 
393 	/*
394 	 * Keep track of signal changes, even when the device is not
395 	 * opened. This allows us to inform upper layers about a
396 	 * possible loss of DCD and thus the existence of a (possibly)
397 	 * different connection when we have DCD back, during the time
398 	 * that the device was closed.
399 	 */
400 	do {
401 		old = sc->sc_ttypend;
402 		new = old & ~SER_MASK_STATE;
403 		new |= sig & SER_INT_SIGMASK;
404 	} while (!atomic_cmpset_32(&sc->sc_ttypend, old, new));
405 
406 	if (sc->sc_opened)
407 		uart_sched_softih(sc, SER_INT_SIGCHG);
408 	return (1);
409 }
410 
411 /*
412  * The transmitter can accept more data.
413  */
414 static __inline int
415 uart_intr_txidle(void *arg)
416 {
417 	struct uart_softc *sc = arg;
418 
419 	if (sc->sc_txbusy) {
420 		sc->sc_txbusy = 0;
421 		uart_sched_softih(sc, SER_INT_TXIDLE);
422 	}
423 	return (0);
424 }
425 
426 static int
427 uart_intr(void *arg)
428 {
429 	struct uart_softc *sc = arg;
430 	int cnt, ipend, testintr;
431 
432 	if (sc->sc_leaving)
433 		return (FILTER_STRAY);
434 
435 	cnt = 0;
436 	testintr = sc->sc_testintr;
437 	while ((!testintr || cnt < 20) && (ipend = UART_IPEND(sc)) != 0) {
438 		cnt++;
439 		if (ipend & SER_INT_OVERRUN)
440 			uart_intr_overrun(sc);
441 		if (ipend & SER_INT_BREAK)
442 			uart_intr_break(sc);
443 		if (ipend & SER_INT_RXREADY)
444 			uart_intr_rxready(sc);
445 		if (ipend & SER_INT_SIGCHG)
446 			uart_intr_sigchg(sc);
447 		if (ipend & SER_INT_TXIDLE)
448 			uart_intr_txidle(sc);
449 	}
450 
451 	if (sc->sc_polled) {
452 		callout_reset(&sc->sc_timer, hz / uart_poll_freq,
453 		    (callout_func_t *)uart_intr, sc);
454 	}
455 
456 	return ((cnt == 0) ? FILTER_STRAY :
457 	    ((testintr && cnt == 20) ? FILTER_SCHEDULE_THREAD :
458 	    FILTER_HANDLED));
459 }
460 
461 serdev_intr_t *
462 uart_bus_ihand(device_t dev, int ipend)
463 {
464 
465 	switch (ipend) {
466 	case SER_INT_BREAK:
467 		return (uart_intr_break);
468 	case SER_INT_OVERRUN:
469 		return (uart_intr_overrun);
470 	case SER_INT_RXREADY:
471 		return (uart_intr_rxready);
472 	case SER_INT_SIGCHG:
473 		return (uart_intr_sigchg);
474 	case SER_INT_TXIDLE:
475 		return (uart_intr_txidle);
476 	}
477 	return (NULL);
478 }
479 
480 int
481 uart_bus_ipend(device_t dev)
482 {
483 	struct uart_softc *sc;
484 
485 	sc = device_get_softc(dev);
486 	return (UART_IPEND(sc));
487 }
488 
489 int
490 uart_bus_sysdev(device_t dev)
491 {
492 	struct uart_softc *sc;
493 
494 	sc = device_get_softc(dev);
495 	return ((sc->sc_sysdev != NULL) ? 1 : 0);
496 }
497 
498 int
499 uart_bus_probe(device_t dev, int regshft, int regiowidth, int rclk, int rid, int chan, int quirks)
500 {
501 	struct uart_softc *sc;
502 	struct uart_devinfo *sysdev;
503 	int error;
504 
505 	sc = device_get_softc(dev);
506 
507 	/*
508 	 * All uart_class references are weak. Check that the needed
509 	 * class has been compiled-in. Fail if not.
510 	 */
511 	if (sc->sc_class == NULL)
512 		return (ENXIO);
513 
514 	/*
515 	 * Initialize the instance. Note that the instance (=softc) does
516 	 * not necessarily match the hardware specific softc. We can't do
517 	 * anything about it now, because we may not attach to the device.
518 	 * Hardware drivers cannot use any of the class specific fields
519 	 * while probing.
520 	 */
521 	kobj_init((kobj_t)sc, (kobj_class_t)sc->sc_class);
522 	sc->sc_dev = dev;
523 	if (device_get_desc(dev) == NULL)
524 		device_set_desc(dev, uart_getname(sc->sc_class));
525 
526 	/*
527 	 * Allocate the register resource. We assume that all UARTs have
528 	 * a single register window in either I/O port space or memory
529 	 * mapped I/O space. Any UART that needs multiple windows will
530 	 * consequently not be supported by this driver as-is. We try I/O
531 	 * port space first because that's the common case.
532 	 */
533 	sc->sc_rrid = rid;
534 	sc->sc_rtype = SYS_RES_IOPORT;
535 	sc->sc_rres = bus_alloc_resource_any(dev, sc->sc_rtype, &sc->sc_rrid,
536 	    RF_ACTIVE);
537 	if (sc->sc_rres == NULL) {
538 		sc->sc_rrid = rid;
539 		sc->sc_rtype = SYS_RES_MEMORY;
540 		sc->sc_rres = bus_alloc_resource_any(dev, sc->sc_rtype,
541 		    &sc->sc_rrid, RF_ACTIVE);
542 		if (sc->sc_rres == NULL)
543 			return (ENXIO);
544 	}
545 
546 	/*
547 	 * Fill in the bus access structure and compare this device with
548 	 * a possible console device and/or a debug port. We set the flags
549 	 * in the softc so that the hardware dependent probe can adjust
550 	 * accordingly. In general, you don't want to permanently disrupt
551 	 * console I/O.
552 	 */
553 	sc->sc_bas.bsh = rman_get_bushandle(sc->sc_rres);
554 	sc->sc_bas.bst = rman_get_bustag(sc->sc_rres);
555 	sc->sc_bas.chan = chan;
556 	sc->sc_bas.regshft = regshft;
557 	sc->sc_bas.regiowidth = regiowidth;
558 	sc->sc_bas.rclk = (rclk == 0) ? sc->sc_class->uc_rclk : rclk;
559 	sc->sc_bas.busy_detect = !!(quirks & UART_F_BUSY_DETECT);
560 
561 	SLIST_FOREACH(sysdev, &uart_sysdevs, next) {
562 		if (chan == sysdev->bas.chan &&
563 		    uart_cpu_eqres(&sc->sc_bas, &sysdev->bas)) {
564 			/* XXX check if ops matches class. */
565 			sc->sc_sysdev = sysdev;
566 			sysdev->bas.rclk = sc->sc_bas.rclk;
567 		}
568 	}
569 
570 	error = UART_PROBE(sc);
571 	bus_release_resource(dev, sc->sc_rtype, sc->sc_rrid, sc->sc_rres);
572 	return ((error) ? error : BUS_PROBE_DEFAULT);
573 }
574 
575 int
576 uart_bus_attach(device_t dev)
577 {
578 	struct uart_softc *sc, *sc0;
579 	const char *sep;
580 	int error, filt;
581 
582 	/*
583 	 * The sc_class field defines the type of UART we're going to work
584 	 * with and thus the size of the softc. Replace the generic softc
585 	 * with one that matches the UART now that we're certain we handle
586 	 * the device.
587 	 */
588 	sc0 = device_get_softc(dev);
589 	if (sc0->sc_class->size > device_get_driver(dev)->size) {
590 		sc = malloc(sc0->sc_class->size, M_UART, M_WAITOK|M_ZERO);
591 		bcopy(sc0, sc, sizeof(*sc));
592 		device_set_softc(dev, sc);
593 	} else
594 		sc = sc0;
595 
596 	/*
597 	 * Now that we know the softc for this device, connect the back
598 	 * pointer from the sysdev for this device, if any
599 	 */
600 	if (sc->sc_sysdev != NULL)
601 		sc->sc_sysdev->sc = sc;
602 
603 	/*
604 	 * Protect ourselves against interrupts while we're not completely
605 	 * finished attaching and initializing. We don't expect interrupts
606 	 * until after UART_ATTACH(), though.
607 	 */
608 	sc->sc_leaving = 1;
609 
610 	mtx_init(&sc->sc_hwmtx_s, "uart_hwmtx", NULL, MTX_SPIN);
611 	if (sc->sc_hwmtx == NULL)
612 		sc->sc_hwmtx = &sc->sc_hwmtx_s;
613 
614 	/*
615 	 * Re-allocate. We expect that the softc contains the information
616 	 * collected by uart_bus_probe() intact.
617 	 */
618 	sc->sc_rres = bus_alloc_resource_any(dev, sc->sc_rtype, &sc->sc_rrid,
619 	    RF_ACTIVE);
620 	if (sc->sc_rres == NULL) {
621 		mtx_destroy(&sc->sc_hwmtx_s);
622 		return (ENXIO);
623 	}
624 	sc->sc_bas.bsh = rman_get_bushandle(sc->sc_rres);
625 	sc->sc_bas.bst = rman_get_bustag(sc->sc_rres);
626 
627 	/*
628 	 * Ensure there is room for at least three full FIFOs of data in the
629 	 * receive buffer (handles the case of low-level drivers with huge
630 	 * FIFOs), and also ensure that there is no less than the historical
631 	 * size of 384 bytes (handles the typical small-FIFO case).
632 	 */
633 	sc->sc_rxbufsz = MAX(384, sc->sc_rxfifosz * 3);
634 	sc->sc_rxbuf = malloc(sc->sc_rxbufsz * sizeof(*sc->sc_rxbuf),
635 	    M_UART, M_WAITOK);
636 	sc->sc_txbuf = malloc(sc->sc_txfifosz * sizeof(*sc->sc_txbuf),
637 	    M_UART, M_WAITOK);
638 
639 	error = UART_ATTACH(sc);
640 	if (error)
641 		goto fail;
642 
643 	if (sc->sc_hwiflow || sc->sc_hwoflow) {
644 		sep = "";
645 		device_print_prettyname(dev);
646 		if (sc->sc_hwiflow) {
647 			printf("%sRTS iflow", sep);
648 			sep = ", ";
649 		}
650 		if (sc->sc_hwoflow) {
651 			printf("%sCTS oflow", sep);
652 			sep = ", ";
653 		}
654 		printf("\n");
655 	}
656 
657 	if (sc->sc_sysdev != NULL) {
658 		if (sc->sc_sysdev->baudrate == 0) {
659 			if (UART_IOCTL(sc, UART_IOCTL_BAUD,
660 			    (intptr_t)&sc->sc_sysdev->baudrate) != 0)
661 				sc->sc_sysdev->baudrate = -1;
662 		}
663 		switch (sc->sc_sysdev->type) {
664 		case UART_DEV_CONSOLE:
665 			device_printf(dev, "console");
666 			break;
667 		case UART_DEV_DBGPORT:
668 			device_printf(dev, "debug port");
669 			break;
670 		case UART_DEV_KEYBOARD:
671 			device_printf(dev, "keyboard");
672 			break;
673 		default:
674 			device_printf(dev, "unknown system device");
675 			break;
676 		}
677 		printf(" (%d,%c,%d,%d)\n", sc->sc_sysdev->baudrate,
678 		    "noems"[sc->sc_sysdev->parity], sc->sc_sysdev->databits,
679 		    sc->sc_sysdev->stopbits);
680 	}
681 
682 	sc->sc_leaving = 0;
683 	sc->sc_testintr = 1;
684 	filt = uart_intr(sc);
685 	sc->sc_testintr = 0;
686 
687 	/*
688 	 * Don't use interrupts if we couldn't clear any pending interrupt
689 	 * conditions. We may have broken H/W and polling is probably the
690 	 * safest thing to do.
691 	 */
692 	if (filt != FILTER_SCHEDULE_THREAD && !uart_force_poll) {
693 		sc->sc_ires = bus_alloc_resource_any(dev, SYS_RES_IRQ,
694 		    &sc->sc_irid, RF_ACTIVE | RF_SHAREABLE);
695 	}
696 	if (sc->sc_ires != NULL) {
697 		error = bus_setup_intr(dev, sc->sc_ires, INTR_TYPE_TTY,
698 		    uart_intr, NULL, sc, &sc->sc_icookie);
699 		sc->sc_fastintr = (error == 0) ? 1 : 0;
700 
701 		if (!sc->sc_fastintr)
702 			error = bus_setup_intr(dev, sc->sc_ires,
703 			    INTR_TYPE_TTY | INTR_MPSAFE, NULL,
704 			    (driver_intr_t *)uart_intr, sc, &sc->sc_icookie);
705 
706 		if (error) {
707 			device_printf(dev, "could not activate interrupt\n");
708 			bus_release_resource(dev, SYS_RES_IRQ, sc->sc_irid,
709 			    sc->sc_ires);
710 			sc->sc_ires = NULL;
711 		}
712 	}
713 	if (sc->sc_ires == NULL) {
714 		/* No interrupt resource. Force polled mode. */
715 		sc->sc_polled = 1;
716 		callout_init(&sc->sc_timer, 1);
717 		callout_reset(&sc->sc_timer, hz / uart_poll_freq,
718 		    (callout_func_t *)uart_intr, sc);
719 	}
720 
721 	if (bootverbose && (sc->sc_fastintr || sc->sc_polled)) {
722 		sep = "";
723 		device_print_prettyname(dev);
724 		if (sc->sc_fastintr) {
725 			printf("%sfast interrupt", sep);
726 			sep = ", ";
727 		}
728 		if (sc->sc_polled) {
729 			printf("%spolled mode (%dHz)", sep, uart_poll_freq);
730 			sep = ", ";
731 		}
732 		printf("\n");
733 	}
734 
735 	if (sc->sc_sysdev != NULL && sc->sc_sysdev->attach != NULL) {
736 		if ((error = sc->sc_sysdev->attach(sc)) != 0)
737 			goto fail;
738 	} else {
739 		if ((error = uart_tty_attach(sc)) != 0)
740 			goto fail;
741 		uart_pps_init(sc);
742 	}
743 
744 	if (sc->sc_sysdev != NULL)
745 		sc->sc_sysdev->hwmtx = sc->sc_hwmtx;
746 
747 	if (sc->sc_rxfifosz > 1)
748 		SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
749 		    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO,
750 		    "rx_overruns", CTLFLAG_RD, &sc->sc_rxoverruns, 0,
751 		    "Receive overruns");
752 
753 	return (0);
754 
755  fail:
756 	free(sc->sc_txbuf, M_UART);
757 	free(sc->sc_rxbuf, M_UART);
758 
759 	if (sc->sc_ires != NULL) {
760 		bus_teardown_intr(dev, sc->sc_ires, sc->sc_icookie);
761 		bus_release_resource(dev, SYS_RES_IRQ, sc->sc_irid,
762 		    sc->sc_ires);
763 	}
764 	bus_release_resource(dev, sc->sc_rtype, sc->sc_rrid, sc->sc_rres);
765 
766 	mtx_destroy(&sc->sc_hwmtx_s);
767 
768 	return (error);
769 }
770 
771 int
772 uart_bus_detach(device_t dev)
773 {
774 	struct uart_softc *sc;
775 
776 	sc = device_get_softc(dev);
777 
778 	sc->sc_leaving = 1;
779 
780 	if (sc->sc_sysdev != NULL)
781 		sc->sc_sysdev->hwmtx = NULL;
782 
783 	UART_DETACH(sc);
784 
785 	if (sc->sc_sysdev != NULL && sc->sc_sysdev->detach != NULL)
786 		(*sc->sc_sysdev->detach)(sc);
787 	else
788 		uart_tty_detach(sc);
789 
790 	free(sc->sc_txbuf, M_UART);
791 	free(sc->sc_rxbuf, M_UART);
792 
793 	if (sc->sc_ires != NULL) {
794 		bus_teardown_intr(dev, sc->sc_ires, sc->sc_icookie);
795 		bus_release_resource(dev, SYS_RES_IRQ, sc->sc_irid,
796 		    sc->sc_ires);
797 	}
798 	bus_release_resource(dev, sc->sc_rtype, sc->sc_rrid, sc->sc_rres);
799 
800 	mtx_destroy(&sc->sc_hwmtx_s);
801 
802 	if (sc->sc_class->size > device_get_driver(dev)->size) {
803 		device_set_softc(dev, NULL);
804 		free(sc, M_UART);
805 	}
806 
807 	return (0);
808 }
809 
810 int
811 uart_bus_resume(device_t dev)
812 {
813 	struct uart_softc *sc;
814 
815 	sc = device_get_softc(dev);
816 	return (UART_ATTACH(sc));
817 }
818 
819 void
820 uart_grab(struct uart_devinfo *di)
821 {
822 
823 	if (di->sc)
824 		UART_GRAB(di->sc);
825 }
826 
827 void
828 uart_ungrab(struct uart_devinfo *di)
829 {
830 
831 	if (di->sc)
832 		UART_UNGRAB(di->sc);
833 }
834