xref: /aosp_15_r20/external/coreboot/src/soc/mediatek/common/pll.c (revision b9411a12aaaa7e1e6a6fb7c5e057f44ee179a49c)
1 /* SPDX-License-Identifier: GPL-2.0-only */
2 
3 #include <device/mmio.h>
4 #include <assert.h>
5 #include <soc/pll.h>
6 #include <types.h>
7 
pll_mux_set_sel(const struct mux * mux,u32 sel)8 void pll_mux_set_sel(const struct mux *mux, u32 sel)
9 {
10 	u32 mask = GENMASK(mux->mux_width - 1, 0);
11 	u32 val = read32(mux->reg);
12 
13 	if (mux->set_reg && mux->clr_reg) {
14 		write32(mux->clr_reg, mask << mux->mux_shift);
15 		write32(mux->set_reg, sel << mux->mux_shift);
16 	} else {
17 		val &= ~(mask << mux->mux_shift);
18 		val |= (sel & mask) << mux->mux_shift;
19 		write32(mux->reg, val);
20 	}
21 
22 	if (mux->upd_reg)
23 		write32(mux->upd_reg, 1 << mux->upd_shift);
24 }
25 
pll_calc_values(const struct pll * pll,u32 * pcw,u32 * postdiv,u32 freq)26 static void pll_calc_values(const struct pll *pll, u32 *pcw, u32 *postdiv,
27 			    u32 freq)
28 {
29 	const u32 fin_hz = CLK26M_HZ;
30 	const u32 *div_rate = pll->div_rate;
31 	u32 val;
32 
33 	assert(freq <= div_rate[0]);
34 	assert(freq >= 1 * GHz / 16);
35 
36 	for (val = 1; div_rate[val] != 0; val++) {
37 		if (freq > div_rate[val])
38 			break;
39 	}
40 	val--;
41 	*postdiv = val;
42 
43 	/* _pcw = freq * 2^postdiv / fin * 2^pcwbits_fractional */
44 	val += pll->pcwbits - PCW_INTEGER_BITS;
45 
46 	*pcw = ((u64)freq << val) / fin_hz;
47 }
48 
pll_set_rate_regs(const struct pll * pll,u32 pcw,u32 postdiv)49 static void pll_set_rate_regs(const struct pll *pll, u32 pcw, u32 postdiv)
50 {
51 	u32 val;
52 
53 	/* set postdiv */
54 	val = read32(pll->div_reg);
55 	val &= ~(PLL_POSTDIV_MASK << pll->div_shift);
56 	val |= postdiv << pll->div_shift;
57 
58 	/* set postdiv and pcw at the same time if on the same register */
59 	if (pll->div_reg != pll->pcw_reg) {
60 		write32(pll->div_reg, val);
61 		val = read32(pll->pcw_reg);
62 	}
63 
64 	/* set pcw */
65 	val &= ~GENMASK(pll->pcw_shift + pll->pcwbits - 1, pll->pcw_shift);
66 	val |= pcw << pll->pcw_shift;
67 	write32(pll->pcw_reg, val);
68 
69 	pll_set_pcw_change(pll);
70 }
71 
pll_set_rate(const struct pll * pll,u32 rate)72 int pll_set_rate(const struct pll *pll, u32 rate)
73 {
74 	u32 pcw, postdiv;
75 
76 	pll_calc_values(pll, &pcw, &postdiv, rate);
77 	pll_set_rate_regs(pll, pcw, postdiv);
78 
79 	return 0;
80 }
81