xref: /aosp_15_r20/external/coreboot/src/drivers/uart/util.c (revision b9411a12aaaa7e1e6a6fb7c5e057f44ee179a49c)
1 /* SPDX-License-Identifier: GPL-2.0-only */
2 
3 #include <console/uart.h>
4 #include <types.h>
5 #include <timer.h>
6 
7 /* Calculate divisor. Do not floor but round to nearest integer. */
uart_baudrate_divisor(unsigned int baudrate,unsigned int refclk,unsigned int oversample)8 unsigned int uart_baudrate_divisor(unsigned int baudrate,
9 	unsigned int refclk, unsigned int oversample)
10 {
11 	return (1 + (2 * refclk) / (baudrate * oversample)) / 2;
12 }
13 
14 #if !CONFIG(UART_OVERRIDE_INPUT_CLOCK_DIVIDER)
uart_input_clock_divider(void)15 unsigned int uart_input_clock_divider(void)
16 {
17 	/* Specify the default oversample rate for the UART.
18 	 *
19 	 * UARTs oversample the receive data.  The UART's input clock first
20 	 * enters the baud-rate divider to generate the oversample clock.  Then
21 	 * the UART typically divides the result by 16.  The asynchronous
22 	 * receive data is synchronized with the oversample clock and when a
23 	 * start bit is detected the UART delays half a bit time using the
24 	 * oversample clock.  Samples are then taken to verify the start bit and
25 	 * if present, samples are taken for the rest of the frame.
26 	 */
27 	return 16;
28 }
29 #endif
30 
31 #if !CONFIG(UART_OVERRIDE_REFCLK)
uart_platform_refclk(void)32 unsigned int uart_platform_refclk(void)
33 {
34 	/* Specify the default input clock frequency for the UART.
35 	 *
36 	 * The older UART's used an input clock frequency of 1.8432 MHz which
37 	 * with the 16x oversampling provided the maximum baud-rate of 115200.
38 	 * Specify this as maximum baud-rate multiplied by oversample so that
39 	 * it is obvious that the maximum baud rate is 115200 when divided by
40 	 * oversample clock.  Also note that crystal on the board does not
41 	 * change when software selects another input clock divider.
42 	 */
43 	return 115200 * 16;
44 }
45 #endif
46 
47 /* Helper function to allow bitbanging an 8n1 UART. */
uart_bitbang_tx_byte(unsigned char data,void (* set_tx)(int line_state))48 void uart_bitbang_tx_byte(unsigned char data, void (*set_tx)(int line_state))
49 {
50 	const int baud_rate = get_uart_baudrate();
51 	int i;
52 	struct stopwatch sw;
53 	stopwatch_init(&sw);
54 
55 	/* Send start bit */
56 	set_tx(0);
57 	while (stopwatch_duration_usecs(&sw) < MHz / baud_rate)
58 		stopwatch_tick(&sw);
59 
60 	/* 'i' counts the total bits sent at the end of the loop */
61 	for (i = 2; i < 10; i++) {
62 		set_tx(data & 1);
63 		data >>= 1;
64 		while (stopwatch_duration_usecs(&sw) < i * MHz / baud_rate)
65 			stopwatch_tick(&sw);
66 	}
67 
68 	/* Send stop bit */
69 	set_tx(1);
70 	while (stopwatch_duration_usecs(&sw) < i * MHz / baud_rate)
71 		stopwatch_tick(&sw);
72 }
73