clk: k210: Move pll into the rest of the driver
[platform/kernel/u-boot.git] / drivers / clk / kendryte / clk.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright (C) 2019-20 Sean Anderson <seanga2@gmail.com>
4  */
5 #define LOG_CATEGORY UCLASS_CLK
6
7 #include <common.h>
8 #include <clk.h>
9 #include <clk-uclass.h>
10 #include <div64.h>
11 #include <dm.h>
12 #include <log.h>
13 #include <mapmem.h>
14 #include <serial.h>
15 #include <dt-bindings/clock/k210-sysctl.h>
16 #include <dt-bindings/mfd/k210-sysctl.h>
17 #include <kendryte/pll.h>
18 #include <linux/bitfield.h>
19
20 /**
21  * struct k210_clk_priv - K210 clock driver private data
22  * @base: The base address of the sysctl device
23  * @in0: The "in0" external oscillator
24  */
25 struct k210_clk_priv {
26         void __iomem *base;
27         struct clk in0;
28 };
29
30 /*
31  * All parameters for different sub-clocks are collected into parameter arrays.
32  * These parameters are then initialized by the clock which uses them during
33  * probe. To save space, ids are automatically generated for each sub-clock by
34  * using an enum. Instead of storing a parameter struct for each clock, even for
35  * those clocks which don't use a particular type of sub-clock, we can just
36  * store the parameters for the clocks which need them.
37  *
38  * So why do it like this? Arranging all the sub-clocks together makes it very
39  * easy to find bugs in the code.
40  */
41
42 /**
43  * enum k210_clk_div_type - The type of divider
44  * @K210_DIV_ONE: freq = parent / (reg + 1)
45  * @K210_DIV_EVEN: freq = parent / 2 / (reg + 1)
46  * @K210_DIV_POWER: freq = parent / (2 << reg)
47  * @K210_DIV_FIXED: freq = parent / factor
48  */
49 enum k210_clk_div_type {
50         K210_DIV_ONE,
51         K210_DIV_EVEN,
52         K210_DIV_POWER,
53         K210_DIV_FIXED,
54 };
55
56 /**
57  * struct k210_div_params - Parameters for dividing clocks
58  * @type: An &enum k210_clk_div_type specifying the dividing formula
59  * @off: The offset of the divider from the sysctl base address
60  * @shift: The offset of the LSB of the divider
61  * @width: The number of bits in the divider
62  * @div: The fixed divisor for this divider
63  */
64 struct k210_div_params {
65         u8 type;
66         union {
67                 struct {
68                         u8 off;
69                         u8 shift;
70                         u8 width;
71                 };
72                 u8 div;
73         };
74 };
75
76 #define DIV_LIST \
77         DIV(K210_CLK_ACLK,   K210_SYSCTL_SEL0,  1,  2, K210_DIV_POWER) \
78         DIV(K210_CLK_APB0,   K210_SYSCTL_SEL0,  3,  3, K210_DIV_ONE) \
79         DIV(K210_CLK_APB1,   K210_SYSCTL_SEL0,  6,  3, K210_DIV_ONE) \
80         DIV(K210_CLK_APB2,   K210_SYSCTL_SEL0,  9,  3, K210_DIV_ONE) \
81         DIV(K210_CLK_SRAM0,  K210_SYSCTL_THR0,  0,  4, K210_DIV_ONE) \
82         DIV(K210_CLK_SRAM1,  K210_SYSCTL_THR0,  4,  4, K210_DIV_ONE) \
83         DIV(K210_CLK_AI,     K210_SYSCTL_THR0,  8,  4, K210_DIV_ONE) \
84         DIV(K210_CLK_DVP,    K210_SYSCTL_THR0, 12,  4, K210_DIV_ONE) \
85         DIV(K210_CLK_ROM,    K210_SYSCTL_THR0, 16,  4, K210_DIV_ONE) \
86         DIV(K210_CLK_SPI0,   K210_SYSCTL_THR1,  0,  8, K210_DIV_EVEN) \
87         DIV(K210_CLK_SPI1,   K210_SYSCTL_THR1,  8,  8, K210_DIV_EVEN) \
88         DIV(K210_CLK_SPI2,   K210_SYSCTL_THR1, 16,  8, K210_DIV_EVEN) \
89         DIV(K210_CLK_SPI3,   K210_SYSCTL_THR1, 24,  8, K210_DIV_EVEN) \
90         DIV(K210_CLK_TIMER0, K210_SYSCTL_THR2,  0,  8, K210_DIV_EVEN) \
91         DIV(K210_CLK_TIMER1, K210_SYSCTL_THR2,  8,  8, K210_DIV_EVEN) \
92         DIV(K210_CLK_TIMER2, K210_SYSCTL_THR2, 16,  8, K210_DIV_EVEN) \
93         DIV(K210_CLK_I2S0,   K210_SYSCTL_THR3,  0, 16, K210_DIV_EVEN) \
94         DIV(K210_CLK_I2S1,   K210_SYSCTL_THR3, 16, 16, K210_DIV_EVEN) \
95         DIV(K210_CLK_I2S2,   K210_SYSCTL_THR4,  0, 16, K210_DIV_EVEN) \
96         DIV(K210_CLK_I2S0_M, K210_SYSCTL_THR4, 16,  8, K210_DIV_EVEN) \
97         DIV(K210_CLK_I2S1_M, K210_SYSCTL_THR4, 24,  8, K210_DIV_EVEN) \
98         DIV(K210_CLK_I2S2_M, K210_SYSCTL_THR4,  0,  8, K210_DIV_EVEN) \
99         DIV(K210_CLK_I2C0,   K210_SYSCTL_THR5,  8,  8, K210_DIV_EVEN) \
100         DIV(K210_CLK_I2C1,   K210_SYSCTL_THR5, 16,  8, K210_DIV_EVEN) \
101         DIV(K210_CLK_I2C2,   K210_SYSCTL_THR5, 24,  8, K210_DIV_EVEN) \
102         DIV(K210_CLK_WDT0,   K210_SYSCTL_THR6,  0,  8, K210_DIV_EVEN) \
103         DIV(K210_CLK_WDT1,   K210_SYSCTL_THR6,  8,  8, K210_DIV_EVEN) \
104         DIV_FIXED(K210_CLK_CLINT, 50) \
105
106 #define _DIVIFY(id) K210_CLK_DIV_##id
107 #define DIVIFY(id) _DIVIFY(id)
108
109 enum k210_div_id {
110 #define DIV(id, ...) DIVIFY(id),
111 #define DIV_FIXED DIV
112         DIV_LIST
113 #undef DIV
114 #undef DIV_FIXED
115         K210_CLK_DIV_NONE,
116 };
117
118 static const struct k210_div_params k210_divs[] = {
119 #define DIV(id, _off, _shift, _width, _type) \
120         [DIVIFY(id)] = { \
121                 .type = (_type), \
122                 .off = (_off), \
123                 .shift = (_shift), \
124                 .width = (_width), \
125         },
126 #define DIV_FIXED(id, _div) \
127         [DIVIFY(id)] = { \
128                 .type = K210_DIV_FIXED, \
129                 .div = (_div) \
130         },
131         DIV_LIST
132 #undef DIV
133 #undef DIV_FIXED
134 };
135
136 #undef DIV
137 #undef DIV_LIST
138
139 /**
140  * struct k210_gate_params - Parameters for gated clocks
141  * @off: The offset of the gate from the sysctl base address
142  * @bit_idx: The index of the bit within the register
143  */
144 struct k210_gate_params {
145         u8 off;
146         u8 bit_idx;
147 };
148
149 #define GATE_LIST \
150         GATE(K210_CLK_CPU,    K210_SYSCTL_EN_CENT,  0) \
151         GATE(K210_CLK_SRAM0,  K210_SYSCTL_EN_CENT,  1) \
152         GATE(K210_CLK_SRAM1,  K210_SYSCTL_EN_CENT,  2) \
153         GATE(K210_CLK_APB0,   K210_SYSCTL_EN_CENT,  3) \
154         GATE(K210_CLK_APB1,   K210_SYSCTL_EN_CENT,  4) \
155         GATE(K210_CLK_APB2,   K210_SYSCTL_EN_CENT,  5) \
156         GATE(K210_CLK_ROM,    K210_SYSCTL_EN_PERI,  0) \
157         GATE(K210_CLK_DMA,    K210_SYSCTL_EN_PERI,  1) \
158         GATE(K210_CLK_AI,     K210_SYSCTL_EN_PERI,  2) \
159         GATE(K210_CLK_DVP,    K210_SYSCTL_EN_PERI,  3) \
160         GATE(K210_CLK_FFT,    K210_SYSCTL_EN_PERI,  4) \
161         GATE(K210_CLK_GPIO,   K210_SYSCTL_EN_PERI,  5) \
162         GATE(K210_CLK_SPI0,   K210_SYSCTL_EN_PERI,  6) \
163         GATE(K210_CLK_SPI1,   K210_SYSCTL_EN_PERI,  7) \
164         GATE(K210_CLK_SPI2,   K210_SYSCTL_EN_PERI,  8) \
165         GATE(K210_CLK_SPI3,   K210_SYSCTL_EN_PERI,  9) \
166         GATE(K210_CLK_I2S0,   K210_SYSCTL_EN_PERI, 10) \
167         GATE(K210_CLK_I2S1,   K210_SYSCTL_EN_PERI, 11) \
168         GATE(K210_CLK_I2S2,   K210_SYSCTL_EN_PERI, 12) \
169         GATE(K210_CLK_I2C0,   K210_SYSCTL_EN_PERI, 13) \
170         GATE(K210_CLK_I2C1,   K210_SYSCTL_EN_PERI, 14) \
171         GATE(K210_CLK_I2C2,   K210_SYSCTL_EN_PERI, 15) \
172         GATE(K210_CLK_UART1,  K210_SYSCTL_EN_PERI, 16) \
173         GATE(K210_CLK_UART2,  K210_SYSCTL_EN_PERI, 17) \
174         GATE(K210_CLK_UART3,  K210_SYSCTL_EN_PERI, 18) \
175         GATE(K210_CLK_AES,    K210_SYSCTL_EN_PERI, 19) \
176         GATE(K210_CLK_FPIOA,  K210_SYSCTL_EN_PERI, 20) \
177         GATE(K210_CLK_TIMER0, K210_SYSCTL_EN_PERI, 21) \
178         GATE(K210_CLK_TIMER1, K210_SYSCTL_EN_PERI, 22) \
179         GATE(K210_CLK_TIMER2, K210_SYSCTL_EN_PERI, 23) \
180         GATE(K210_CLK_WDT0,   K210_SYSCTL_EN_PERI, 24) \
181         GATE(K210_CLK_WDT1,   K210_SYSCTL_EN_PERI, 25) \
182         GATE(K210_CLK_SHA,    K210_SYSCTL_EN_PERI, 26) \
183         GATE(K210_CLK_OTP,    K210_SYSCTL_EN_PERI, 27) \
184         GATE(K210_CLK_RTC,    K210_SYSCTL_EN_PERI, 29)
185
186 #define _GATEIFY(id) K210_CLK_GATE_##id
187 #define GATEIFY(id) _GATEIFY(id)
188
189 enum k210_gate_id {
190 #define GATE(id, ...) GATEIFY(id),
191         GATE_LIST
192 #undef GATE
193         K210_CLK_GATE_NONE,
194 };
195
196 static const struct k210_gate_params k210_gates[] = {
197 #define GATE(id, _off, _idx) \
198         [GATEIFY(id)] = { \
199                 .off = (_off), \
200                 .bit_idx = (_idx), \
201         },
202         GATE_LIST
203 #undef GATE
204 };
205
206 #undef GATE_LIST
207
208 /* The most parents is PLL2 */
209 #define K210_CLK_MAX_PARENTS 3
210
211 /**
212  * struct k210_mux_params - Parameters for muxed clocks
213  * @parents: A list of parent clock ids
214  * @num_parents: The number of parent clocks
215  * @off: The offset of the mux from the base sysctl address
216  * @shift: The offset of the LSB of the mux selector
217  * @width: The number of bits in the mux selector
218  */
219 struct k210_mux_params {
220         u8 parents[K210_CLK_MAX_PARENTS];
221         u8 num_parents;
222         u8 off;
223         u8 shift;
224         u8 width;
225 };
226
227 #define MUX(id, reg, shift, width) \
228         MUX_PARENTS(id, reg, shift, width, K210_CLK_IN0, K210_CLK_PLL0)
229 #define MUX_LIST \
230         MUX_PARENTS(K210_CLK_PLL2, K210_SYSCTL_PLL2, 26, 2, \
231                     K210_CLK_IN0, K210_CLK_PLL0, K210_CLK_PLL1) \
232         MUX(K210_CLK_ACLK, K210_SYSCTL_SEL0, 0, 1) \
233         MUX(K210_CLK_SPI3,   K210_SYSCTL_SEL0, 12, 1) \
234         MUX(K210_CLK_TIMER0, K210_SYSCTL_SEL0, 13, 1) \
235         MUX(K210_CLK_TIMER1, K210_SYSCTL_SEL0, 14, 1) \
236         MUX(K210_CLK_TIMER2, K210_SYSCTL_SEL0, 15, 1)
237
238 #define _MUXIFY(id) K210_CLK_MUX_##id
239 #define MUXIFY(id) _MUXIFY(id)
240
241 enum k210_mux_id {
242 #define MUX_PARENTS(id, ...) MUXIFY(id),
243         MUX_LIST
244 #undef MUX_PARENTS
245         K210_CLK_MUX_NONE,
246 };
247
248 static const struct k210_mux_params k210_muxes[] = {
249 #define MUX_PARENTS(id, _off, _shift, _width, ...) \
250         [MUXIFY(id)] = { \
251                 .parents = { __VA_ARGS__ }, \
252                 .num_parents = __count_args(__VA_ARGS__), \
253                 .off = (_off), \
254                 .shift = (_shift), \
255                 .width = (_width), \
256         },
257         MUX_LIST
258 #undef MUX_PARENTS
259 };
260
261 #undef MUX
262 #undef MUX_LIST
263
264 /**
265  * struct k210_pll_params - K210 PLL parameters
266  * @off: The offset of the PLL from the base sysctl address
267  * @shift: The offset of the LSB of the lock status
268  * @width: The number of bits in the lock status
269  */
270 struct k210_pll_params {
271         u8 off;
272         u8 shift;
273         u8 width;
274 };
275
276 static const struct k210_pll_params k210_plls[] = {
277 #define PLL(_off, _shift, _width) { \
278         .off = (_off), \
279         .shift = (_shift), \
280         .width = (_width), \
281 }
282         [0] = PLL(K210_SYSCTL_PLL0,  0, 2),
283         [1] = PLL(K210_SYSCTL_PLL1,  8, 1),
284         [2] = PLL(K210_SYSCTL_PLL2, 16, 1),
285 #undef PLL
286 };
287
288 /**
289  * enum k210_clk_flags - The type of a K210 clock
290  * @K210_CLKF_MUX: This clock has a mux and not a static parent
291  * @K210_CLKF_PLL: This clock is a PLL
292  */
293 enum k210_clk_flags {
294         K210_CLKF_MUX = BIT(0),
295         K210_CLKF_PLL = BIT(1),
296 };
297
298 /**
299  * struct k210_clk_params - The parameters defining a K210 clock
300  * @name: The name of the clock
301  * @flags: A set of &enum k210_clk_flags defining which fields are valid
302  * @mux: An &enum k210_mux_id of this clock's mux
303  * @parent: The clock id of this clock's parent
304  * @pll: The id of the PLL (if this clock is a PLL)
305  * @div: An &enum k210_div_id of this clock's divider
306  * @gate: An &enum k210_gate_id of this clock's gate
307  */
308 struct k210_clk_params {
309 #if CONFIG_IS_ENABLED(CMD_CLK)
310         const char *name;
311 #endif
312         u8 flags;
313         union {
314                 u8 parent;
315                 u8 mux;
316         };
317         union {
318                 u8 pll;
319                 struct {
320                         u8 div;
321                         u8 gate;
322                 };
323         };
324 };
325
326 static const struct k210_clk_params k210_clks[] = {
327 #if CONFIG_IS_ENABLED(CMD_CLK)
328 #define NAME(_name) .name = (_name),
329 #else
330 #define NAME(name)
331 #endif
332 #define CLK(id, _name, _parent, _div, _gate) \
333         [id] = { \
334                 NAME(_name) \
335                 .parent = (_parent), \
336                 .div = (_div), \
337                 .gate = (_gate), \
338         }
339 #define CLK_MUX(id, _name, _mux, _div, _gate) \
340         [id] = { \
341                 NAME(_name) \
342                 .flags = K210_CLKF_MUX, \
343                 .mux = (_mux), \
344                 .div = (_div), \
345                 .gate = (_gate), \
346         }
347 #define CLK_PLL(id, _pll, _parent) \
348         [id] = { \
349                 NAME("pll" #_pll) \
350                 .flags = K210_CLKF_PLL, \
351                 .parent = (_parent), \
352                 .pll = (_pll), \
353         }
354 #define CLK_FULL(id, name) \
355         CLK_MUX(id, name, MUXIFY(id), DIVIFY(id), GATEIFY(id))
356 #define CLK_NOMUX(id, name, parent) \
357         CLK(id, name, parent, DIVIFY(id), GATEIFY(id))
358 #define CLK_DIV(id, name, parent) \
359         CLK(id, name, parent, DIVIFY(id), K210_CLK_GATE_NONE)
360 #define CLK_GATE(id, name, parent) \
361         CLK(id, name, parent, K210_CLK_DIV_NONE, GATEIFY(id))
362         CLK_PLL(K210_CLK_PLL0, 0, K210_CLK_IN0),
363         CLK_PLL(K210_CLK_PLL1, 1, K210_CLK_IN0),
364         [K210_CLK_PLL2] = {
365                 NAME("pll2")
366                 .flags = K210_CLKF_MUX | K210_CLKF_PLL,
367                 .mux = MUXIFY(K210_CLK_PLL2),
368                 .pll = 2,
369         },
370         CLK_MUX(K210_CLK_ACLK, "aclk", MUXIFY(K210_CLK_ACLK),
371                 DIVIFY(K210_CLK_ACLK), K210_CLK_GATE_NONE),
372         CLK_FULL(K210_CLK_SPI3,   "spi3"),
373         CLK_FULL(K210_CLK_TIMER0, "timer0"),
374         CLK_FULL(K210_CLK_TIMER1, "timer1"),
375         CLK_FULL(K210_CLK_TIMER2, "timer2"),
376         CLK_NOMUX(K210_CLK_SRAM0, "sram0",  K210_CLK_ACLK),
377         CLK_NOMUX(K210_CLK_SRAM1, "sram1",  K210_CLK_ACLK),
378         CLK_NOMUX(K210_CLK_ROM,   "rom",    K210_CLK_ACLK),
379         CLK_NOMUX(K210_CLK_DVP,   "dvp",    K210_CLK_ACLK),
380         CLK_NOMUX(K210_CLK_APB0,  "apb0",   K210_CLK_ACLK),
381         CLK_NOMUX(K210_CLK_APB1,  "apb1",   K210_CLK_ACLK),
382         CLK_NOMUX(K210_CLK_APB2,  "apb2",   K210_CLK_ACLK),
383         CLK_NOMUX(K210_CLK_AI,    "ai",     K210_CLK_PLL1),
384         CLK_NOMUX(K210_CLK_I2S0,  "i2s0",   K210_CLK_PLL2),
385         CLK_NOMUX(K210_CLK_I2S1,  "i2s1",   K210_CLK_PLL2),
386         CLK_NOMUX(K210_CLK_I2S2,  "i2s2",   K210_CLK_PLL2),
387         CLK_NOMUX(K210_CLK_WDT0,  "wdt0",   K210_CLK_IN0),
388         CLK_NOMUX(K210_CLK_WDT1,  "wdt1",   K210_CLK_IN0),
389         CLK_NOMUX(K210_CLK_SPI0,  "spi0",   K210_CLK_PLL0),
390         CLK_NOMUX(K210_CLK_SPI1,  "spi1",   K210_CLK_PLL0),
391         CLK_NOMUX(K210_CLK_SPI2,  "spi2",   K210_CLK_PLL0),
392         CLK_NOMUX(K210_CLK_I2C0,  "i2c0",   K210_CLK_PLL0),
393         CLK_NOMUX(K210_CLK_I2C1,  "i2c1",   K210_CLK_PLL0),
394         CLK_NOMUX(K210_CLK_I2C2,  "i2c2",   K210_CLK_PLL0),
395         CLK_DIV(K210_CLK_I2S0_M,  "i2s0_m", K210_CLK_PLL2),
396         CLK_DIV(K210_CLK_I2S1_M,  "i2s1_m", K210_CLK_PLL2),
397         CLK_DIV(K210_CLK_I2S2_M,  "i2s2_m", K210_CLK_PLL2),
398         CLK_DIV(K210_CLK_CLINT,   "clint",  K210_CLK_ACLK),
399         CLK_GATE(K210_CLK_CPU,    "cpu",    K210_CLK_ACLK),
400         CLK_GATE(K210_CLK_DMA,    "dma",    K210_CLK_ACLK),
401         CLK_GATE(K210_CLK_FFT,    "fft",    K210_CLK_ACLK),
402         CLK_GATE(K210_CLK_GPIO,   "gpio",   K210_CLK_APB0),
403         CLK_GATE(K210_CLK_UART1,  "uart1",  K210_CLK_APB0),
404         CLK_GATE(K210_CLK_UART2,  "uart2",  K210_CLK_APB0),
405         CLK_GATE(K210_CLK_UART3,  "uart3",  K210_CLK_APB0),
406         CLK_GATE(K210_CLK_FPIOA,  "fpioa",  K210_CLK_APB0),
407         CLK_GATE(K210_CLK_SHA,    "sha",    K210_CLK_APB0),
408         CLK_GATE(K210_CLK_AES,    "aes",    K210_CLK_APB1),
409         CLK_GATE(K210_CLK_OTP,    "otp",    K210_CLK_APB1),
410         CLK_GATE(K210_CLK_RTC,    "rtc",    K210_CLK_IN0),
411 #undef NAME
412 #undef CLK_PLL
413 #undef CLK
414 #undef CLK_FULL
415 #undef CLK_NOMUX
416 #undef CLK_DIV
417 #undef CLK_GATE
418 #undef CLK_LIST
419 };
420
421 #define K210_PLL_CLKR           GENMASK(3, 0)
422 #define K210_PLL_CLKF           GENMASK(9, 4)
423 #define K210_PLL_CLKOD          GENMASK(13, 10) /* Output Divider */
424 #define K210_PLL_BWADJ          GENMASK(19, 14) /* BandWidth Adjust */
425 #define K210_PLL_RESET          BIT(20)
426 #define K210_PLL_PWRD           BIT(21) /* PoWeReD */
427 #define K210_PLL_INTFB          BIT(22) /* Internal FeedBack */
428 #define K210_PLL_BYPASS         BIT(23)
429 #define K210_PLL_TEST           BIT(24)
430 #define K210_PLL_EN             BIT(25)
431 #define K210_PLL_TEST_EN        BIT(26)
432
433 #define K210_PLL_LOCK           0
434 #define K210_PLL_CLEAR_SLIP     2
435 #define K210_PLL_TEST_OUT       3
436
437 #ifdef CONFIG_CLK_K210_SET_RATE
438 static int k210_pll_enable(struct k210_clk_priv *priv, int id);
439 static int k210_pll_disable(struct k210_clk_priv *priv, int id);
440 static ulong k210_pll_get_rate(struct k210_clk_priv *priv, int id, ulong rate_in);
441
442 /*
443  * The PLL included with the Kendryte K210 appears to be a True Circuits, Inc.
444  * General-Purpose PLL. The logical layout of the PLL with internal feedback is
445  * approximately the following:
446  *
447  *  +---------------+
448  *  |reference clock|
449  *  +---------------+
450  *          |
451  *          v
452  *        +--+
453  *        |/r|
454  *        +--+
455  *          |
456  *          v
457  *   +-------------+
458  *   |divided clock|
459  *   +-------------+
460  *          |
461  *          v
462  *  +--------------+
463  *  |phase detector|<---+
464  *  +--------------+    |
465  *          |           |
466  *          v   +--------------+
467  *        +---+ |feedback clock|
468  *        |VCO| +--------------+
469  *        +---+         ^
470  *          |    +--+   |
471  *          +--->|/f|---+
472  *          |    +--+
473  *          v
474  *        +---+
475  *        |/od|
476  *        +---+
477  *          |
478  *          v
479  *       +------+
480  *       |output|
481  *       +------+
482  *
483  * The k210 PLLs have three factors: r, f, and od. Because of the feedback mode,
484  * the effect of the division by f is to multiply the input frequency. The
485  * equation for the output rate is
486  *   rate = (rate_in * f) / (r * od).
487  * Moving knowns to one side of the equation, we get
488  *   rate / rate_in = f / (r * od)
489  * Rearranging slightly,
490  *   abs_error = abs((rate / rate_in) - (f / (r * od))).
491  * To get relative, error, we divide by the expected ratio
492  *   error = abs((rate / rate_in) - (f / (r * od))) / (rate / rate_in).
493  * Simplifying,
494  *   error = abs(1 - f / (r * od)) / (rate / rate_in)
495  *   error = abs(1 - (f * rate_in) / (r * od * rate))
496  * Using the constants ratio = rate / rate_in and inv_ratio = rate_in / rate,
497  *   error = abs((f * inv_ratio) / (r * od) - 1)
498  * This is the error used in evaluating parameters.
499  *
500  * r and od are four bits each, while f is six bits. Because r and od are
501  * multiplied together, instead of the full 256 values possible if both bits
502  * were used fully, there are only 97 distinct products. Combined with f, there
503  * are 6208 theoretical settings for the PLL. However, most of these settings
504  * can be ruled out immediately because they do not have the correct ratio.
505  *
506  * In addition to the constraint of approximating the desired ratio, parameters
507  * must also keep internal pll frequencies within acceptable ranges. The divided
508  * clock's minimum and maximum frequencies have a ratio of around 128.  This
509  * leaves fairly substantial room to work with, especially since the only
510  * affected parameter is r. The VCO's minimum and maximum frequency have a ratio
511  * of 5, which is considerably more restrictive.
512  *
513  * The r and od factors are stored in a table. This is to make it easy to find
514  * the next-largest product. Some products have multiple factorizations, but
515  * only when one factor has at least a 2.5x ratio to the factors of the other
516  * factorization. This is because any smaller ratio would not make a difference
517  * when ensuring the VCO's frequency is within spec.
518  *
519  * Throughout the calculation function, fixed point arithmetic is used. Because
520  * the range of rate and rate_in may be up to 1.75 GHz, or around 2^30, 64-bit
521  * 32.32 fixed-point numbers are used to represent ratios. In general, to
522  * implement division, the numerator is first multiplied by 2^32. This gives a
523  * result where the whole number part is in the upper 32 bits, and the fraction
524  * is in the lower 32 bits.
525  *
526  * In general, rounding is done to the closest integer. This helps find the best
527  * approximation for the ratio. Rounding in one direction (e.g down) could cause
528  * the function to miss a better ratio with one of the parameters increased by
529  * one.
530  */
531
532 /*
533  * The factors table was generated with the following python code:
534  *
535  * def p(x, y):
536  *    return (1.0*x/y > 2.5) or (1.0*y/x > 2.5)
537  *
538  * factors = {}
539  * for i in range(1, 17):
540  *    for j in range(1, 17):
541  *       fs = factors.get(i*j) or []
542  *       if fs == [] or all([
543  *             (p(i, x) and p(i, y)) or (p(j, x) and p(j, y))
544  *             for (x, y) in fs]):
545  *          fs.append((i, j))
546  *          factors[i*j] = fs
547  *
548  * for k, l in sorted(factors.items()):
549  *    for v in l:
550  *       print("PACK(%s, %s)," % v)
551  */
552 #define PACK(r, od) (((((r) - 1) & 0xF) << 4) | (((od) - 1) & 0xF))
553 #define UNPACK_R(val) ((((val) >> 4) & 0xF) + 1)
554 #define UNPACK_OD(val) (((val) & 0xF) + 1)
555 static const u8 factors[] = {
556         PACK(1, 1),
557         PACK(1, 2),
558         PACK(1, 3),
559         PACK(1, 4),
560         PACK(1, 5),
561         PACK(1, 6),
562         PACK(1, 7),
563         PACK(1, 8),
564         PACK(1, 9),
565         PACK(3, 3),
566         PACK(1, 10),
567         PACK(1, 11),
568         PACK(1, 12),
569         PACK(3, 4),
570         PACK(1, 13),
571         PACK(1, 14),
572         PACK(1, 15),
573         PACK(3, 5),
574         PACK(1, 16),
575         PACK(4, 4),
576         PACK(2, 9),
577         PACK(2, 10),
578         PACK(3, 7),
579         PACK(2, 11),
580         PACK(2, 12),
581         PACK(5, 5),
582         PACK(2, 13),
583         PACK(3, 9),
584         PACK(2, 14),
585         PACK(2, 15),
586         PACK(2, 16),
587         PACK(3, 11),
588         PACK(5, 7),
589         PACK(3, 12),
590         PACK(3, 13),
591         PACK(4, 10),
592         PACK(3, 14),
593         PACK(4, 11),
594         PACK(3, 15),
595         PACK(3, 16),
596         PACK(7, 7),
597         PACK(5, 10),
598         PACK(4, 13),
599         PACK(6, 9),
600         PACK(5, 11),
601         PACK(4, 14),
602         PACK(4, 15),
603         PACK(7, 9),
604         PACK(4, 16),
605         PACK(5, 13),
606         PACK(6, 11),
607         PACK(5, 14),
608         PACK(6, 12),
609         PACK(5, 15),
610         PACK(7, 11),
611         PACK(6, 13),
612         PACK(5, 16),
613         PACK(9, 9),
614         PACK(6, 14),
615         PACK(8, 11),
616         PACK(6, 15),
617         PACK(7, 13),
618         PACK(6, 16),
619         PACK(7, 14),
620         PACK(9, 11),
621         PACK(10, 10),
622         PACK(8, 13),
623         PACK(7, 15),
624         PACK(9, 12),
625         PACK(10, 11),
626         PACK(7, 16),
627         PACK(9, 13),
628         PACK(8, 15),
629         PACK(11, 11),
630         PACK(9, 14),
631         PACK(8, 16),
632         PACK(10, 13),
633         PACK(11, 12),
634         PACK(9, 15),
635         PACK(10, 14),
636         PACK(11, 13),
637         PACK(9, 16),
638         PACK(10, 15),
639         PACK(11, 14),
640         PACK(12, 13),
641         PACK(10, 16),
642         PACK(11, 15),
643         PACK(12, 14),
644         PACK(13, 13),
645         PACK(11, 16),
646         PACK(12, 15),
647         PACK(13, 14),
648         PACK(12, 16),
649         PACK(13, 15),
650         PACK(14, 14),
651         PACK(13, 16),
652         PACK(14, 15),
653         PACK(14, 16),
654         PACK(15, 15),
655         PACK(15, 16),
656         PACK(16, 16),
657 };
658
659 TEST_STATIC int k210_pll_calc_config(u32 rate, u32 rate_in,
660                                      struct k210_pll_config *best)
661 {
662         int i;
663         s64 error, best_error;
664         u64 ratio, inv_ratio; /* fixed point 32.32 ratio of the rates */
665         u64 max_r;
666         u64 r, f, od;
667
668         /*
669          * Can't go over 1.75 GHz or under 21.25 MHz due to limitations on the
670          * VCO frequency. These are not the same limits as below because od can
671          * reduce the output frequency by 16.
672          */
673         if (rate > 1750000000 || rate < 21250000)
674                 return -EINVAL;
675
676         /* Similar restrictions on the input rate */
677         if (rate_in > 1750000000 || rate_in < 13300000)
678                 return -EINVAL;
679
680         ratio = DIV_ROUND_CLOSEST_ULL((u64)rate << 32, rate_in);
681         inv_ratio = DIV_ROUND_CLOSEST_ULL((u64)rate_in << 32, rate);
682         /* Can't increase by more than 64 or reduce by more than 256 */
683         if (rate > rate_in && ratio > (64ULL << 32))
684                 return -EINVAL;
685         else if (rate <= rate_in && inv_ratio > (256ULL << 32))
686                 return -EINVAL;
687
688         /*
689          * The divided clock (rate_in / r) must stay between 1.75 GHz and 13.3
690          * MHz. There is no minimum, since the only way to get a higher input
691          * clock than 26 MHz is to use a clock generated by a PLL. Because PLLs
692          * cannot output frequencies greater than 1.75 GHz, the minimum would
693          * never be greater than one.
694          */
695         max_r = DIV_ROUND_DOWN_ULL(rate_in, 13300000);
696
697         /* Variables get immediately incremented, so start at -1th iteration */
698         i = -1;
699         f = 0;
700         r = 0;
701         od = 0;
702         best_error = S64_MAX;
703         error = best_error;
704         /* do-while here so we always try at least one ratio */
705         do {
706                 /*
707                  * Whether we swapped r and od while enforcing frequency limits
708                  */
709                 bool swapped = false;
710                 u64 last_od = od;
711                 u64 last_r = r;
712
713                 /*
714                  * Try the next largest value for f (or r and od) and
715                  * recalculate the other parameters based on that
716                  */
717                 if (rate > rate_in) {
718                         /*
719                          * Skip factors of the same product if we already tried
720                          * out that product
721                          */
722                         do {
723                                 i++;
724                                 r = UNPACK_R(factors[i]);
725                                 od = UNPACK_OD(factors[i]);
726                         } while (i + 1 < ARRAY_SIZE(factors) &&
727                                  r * od == last_r * last_od);
728
729                         /* Round close */
730                         f = (r * od * ratio + BIT(31)) >> 32;
731                         if (f > 64)
732                                 f = 64;
733                 } else {
734                         u64 tmp = ++f * inv_ratio;
735                         bool round_up = !!(tmp & BIT(31));
736                         u32 goal = (tmp >> 32) + round_up;
737                         u32 err, last_err;
738
739                         /* Get the next r/od pair in factors */
740                         while (r * od < goal && i + 1 < ARRAY_SIZE(factors)) {
741                                 i++;
742                                 r = UNPACK_R(factors[i]);
743                                 od = UNPACK_OD(factors[i]);
744                         }
745
746                         /*
747                          * This is a case of double rounding. If we rounded up
748                          * above, we need to round down (in cases of ties) here.
749                          * This prevents off-by-one errors resulting from
750                          * choosing X+2 over X when X.Y rounds up to X+1 and
751                          * there is no r * od = X+1. For the converse, when X.Y
752                          * is rounded down to X, we should choose X+1 over X-1.
753                          */
754                         err = abs(r * od - goal);
755                         last_err = abs(last_r * last_od - goal);
756                         if (last_err < err || (round_up && last_err == err)) {
757                                 i--;
758                                 r = last_r;
759                                 od = last_od;
760                         }
761                 }
762
763                 /*
764                  * Enforce limits on internal clock frequencies. If we
765                  * aren't in spec, try swapping r and od. If everything is
766                  * in-spec, calculate the relative error.
767                  */
768                 while (true) {
769                         /*
770                          * Whether the intermediate frequencies are out-of-spec
771                          */
772                         bool out_of_spec = false;
773
774                         if (r > max_r) {
775                                 out_of_spec = true;
776                         } else {
777                                 /*
778                                  * There is no way to only divide once; we need
779                                  * to examine the frequency with and without the
780                                  * effect of od.
781                                  */
782                                 u64 vco = DIV_ROUND_CLOSEST_ULL(rate_in * f, r);
783
784                                 if (vco > 1750000000 || vco < 340000000)
785                                         out_of_spec = true;
786                         }
787
788                         if (out_of_spec) {
789                                 if (!swapped) {
790                                         u64 tmp = r;
791
792                                         r = od;
793                                         od = tmp;
794                                         swapped = true;
795                                         continue;
796                                 } else {
797                                         /*
798                                          * Try looking ahead to see if there are
799                                          * additional factors for the same
800                                          * product.
801                                          */
802                                         if (i + 1 < ARRAY_SIZE(factors)) {
803                                                 u64 new_r, new_od;
804
805                                                 i++;
806                                                 new_r = UNPACK_R(factors[i]);
807                                                 new_od = UNPACK_OD(factors[i]);
808                                                 if (r * od == new_r * new_od) {
809                                                         r = new_r;
810                                                         od = new_od;
811                                                         swapped = false;
812                                                         continue;
813                                                 }
814                                                 i--;
815                                         }
816                                         break;
817                                 }
818                         }
819
820                         error = DIV_ROUND_CLOSEST_ULL(f * inv_ratio, r * od);
821                         /* The lower 16 bits are spurious */
822                         error = abs((error - BIT(32))) >> 16;
823
824                         if (error < best_error) {
825                                 best->r = r;
826                                 best->f = f;
827                                 best->od = od;
828                                 best_error = error;
829                         }
830                         break;
831                 }
832         } while (f < 64 && i + 1 < ARRAY_SIZE(factors) && error != 0);
833
834         if (best_error == S64_MAX)
835                 return -EINVAL;
836
837         log_debug("best error %lld\n", best_error);
838         return 0;
839 }
840
841 static ulong k210_pll_set_rate(struct k210_clk_priv *priv, int id, ulong rate,
842                                ulong rate_in)
843 {
844         int err;
845         const struct k210_pll_params *pll = &k210_plls[id];
846         struct k210_pll_config config = {};
847         u32 reg;
848
849         if (rate_in < 0)
850                 return rate_in;
851
852         log_debug("Calculating parameters with rate=%lu and rate_in=%lu\n",
853                   rate, rate_in);
854         err = k210_pll_calc_config(rate, rate_in, &config);
855         if (err)
856                 return err;
857         log_debug("Got r=%u f=%u od=%u\n", config.r, config.f, config.od);
858
859         /*
860          * Don't use clk_disable as it might not actually disable the pll due to
861          * refcounting
862          */
863         k210_pll_disable(priv, id);
864
865         reg = readl(priv->base + pll->off);
866         reg &= ~K210_PLL_CLKR
867             &  ~K210_PLL_CLKF
868             &  ~K210_PLL_CLKOD
869             &  ~K210_PLL_BWADJ;
870         reg |= FIELD_PREP(K210_PLL_CLKR, config.r - 1)
871             |  FIELD_PREP(K210_PLL_CLKF, config.f - 1)
872             |  FIELD_PREP(K210_PLL_CLKOD, config.od - 1)
873             |  FIELD_PREP(K210_PLL_BWADJ, config.f - 1);
874         writel(reg, priv->base + pll->off);
875
876         err = k210_pll_enable(priv, id);
877
878         serial_setbrg();
879         return k210_pll_get_rate(priv, id, rate);
880 }
881 #else
882 static ulong k210_pll_set_rate(struct k210_clk_priv *priv, int id, ulong rate,
883                                ulong rate_in)
884 {
885         return -ENOSYS;
886 }
887 #endif /* CONFIG_CLK_K210_SET_RATE */
888
889 static ulong k210_pll_get_rate(struct k210_clk_priv *priv, int id,
890                                ulong rate_in)
891 {
892         u64 r, f, od;
893         u32 reg = readl(priv->base + k210_plls[id].off);
894
895         if (rate_in < 0 || (reg & K210_PLL_BYPASS))
896                 return rate_in;
897
898         if (!(reg & K210_PLL_PWRD))
899                 return 0;
900
901         r = FIELD_GET(K210_PLL_CLKR, reg) + 1;
902         f = FIELD_GET(K210_PLL_CLKF, reg) + 1;
903         od = FIELD_GET(K210_PLL_CLKOD, reg) + 1;
904
905         return DIV_ROUND_DOWN_ULL(((u64)rate_in) * f, r * od);
906 }
907
908 /*
909  * Wait for the PLL to be locked. If the PLL is not locked, try clearing the
910  * slip before retrying
911  */
912 static void k210_pll_waitfor_lock(struct k210_clk_priv *priv, int id)
913 {
914         const struct k210_pll_params *pll = &k210_plls[id];
915         u32 mask = (BIT(pll->width) - 1) << pll->shift;
916
917         while (true) {
918                 u32 reg = readl(priv->base + K210_SYSCTL_PLL_LOCK);
919
920                 if ((reg & mask) == mask)
921                         break;
922
923                 reg |= BIT(pll->shift + K210_PLL_CLEAR_SLIP);
924                 writel(reg, priv->base + K210_SYSCTL_PLL_LOCK);
925         }
926 }
927
928 /* Adapted from sysctl_pll_enable */
929 static int k210_pll_enable(struct k210_clk_priv *priv, int id)
930 {
931         const struct k210_pll_params *pll = &k210_plls[id];
932         u32 reg = readl(priv->base + pll->off);
933
934         if ((reg & K210_PLL_PWRD) && (reg & K210_PLL_EN) &&
935             !(reg & K210_PLL_RESET))
936                 return 0;
937
938         reg |= K210_PLL_PWRD;
939         writel(reg, priv->base + pll->off);
940
941         /* Ensure reset is low before asserting it */
942         reg &= ~K210_PLL_RESET;
943         writel(reg, priv->base + pll->off);
944         reg |= K210_PLL_RESET;
945         writel(reg, priv->base + pll->off);
946         nop();
947         nop();
948         reg &= ~K210_PLL_RESET;
949         writel(reg, priv->base + pll->off);
950
951         k210_pll_waitfor_lock(priv, id);
952
953         reg &= ~K210_PLL_BYPASS;
954         reg |= K210_PLL_EN;
955         writel(reg, priv->base + pll->off);
956
957         return 0;
958 }
959
960 static int k210_pll_disable(struct k210_clk_priv *priv, int id)
961 {
962         const struct k210_pll_params *pll = &k210_plls[id];
963         u32 reg = readl(priv->base + pll->off);
964
965         /*
966          * Bypassing before powering off is important so child clocks don't stop
967          * working. This is especially important for pll0, the indirect parent
968          * of the cpu clock.
969          */
970         reg |= K210_PLL_BYPASS;
971         writel(reg, priv->base + pll->off);
972
973         reg &= ~K210_PLL_PWRD;
974         reg &= ~K210_PLL_EN;
975         writel(reg, priv->base + pll->off);
976         return 0;
977 }
978
979 static u32 k210_clk_readl(struct k210_clk_priv *priv, u8 off, u8 shift,
980                           u8 width)
981 {
982         u32 reg = readl(priv->base + off);
983
984         return (reg >> shift) & (BIT(width) - 1);
985 }
986
987 static void k210_clk_writel(struct k210_clk_priv *priv, u8 off, u8 shift,
988                             u8 width, u32 val)
989 {
990         u32 reg = readl(priv->base + off);
991         u32 mask = (BIT(width) - 1) << shift;
992
993         reg &= ~mask;
994         reg |= mask & (val << shift);
995         writel(reg, priv->base + off);
996 }
997
998 static int k210_clk_get_parent(struct k210_clk_priv *priv, int id)
999 {
1000         u32 sel;
1001         const struct k210_mux_params *mux;
1002
1003         if (!(k210_clks[id].flags & K210_CLKF_MUX))
1004                 return k210_clks[id].parent;
1005         mux = &k210_muxes[k210_clks[id].mux];
1006
1007         sel = k210_clk_readl(priv, mux->off, mux->shift, mux->width);
1008         assert(sel < mux->num_parents);
1009         return mux->parents[sel];
1010 }
1011
1012 static ulong do_k210_clk_get_rate(struct k210_clk_priv *priv, int id)
1013 {
1014         int parent;
1015         u32 val;
1016         ulong parent_rate;
1017         const struct k210_div_params *div;
1018
1019         if (id == K210_CLK_IN0)
1020                 return clk_get_rate(&priv->in0);
1021
1022         parent = k210_clk_get_parent(priv, id);
1023         parent_rate = do_k210_clk_get_rate(priv, parent);
1024
1025         if (k210_clks[id].flags & K210_CLKF_PLL)
1026                 return k210_pll_get_rate(priv, k210_clks[id].pll, parent_rate);
1027
1028         if (k210_clks[id].div == K210_CLK_DIV_NONE)
1029                 return parent_rate;
1030         div = &k210_divs[k210_clks[id].div];
1031
1032         if (div->type == K210_DIV_FIXED)
1033                 return parent_rate / div->div;
1034
1035         val = k210_clk_readl(priv, div->off, div->shift, div->width);
1036         switch (div->type) {
1037         case K210_DIV_ONE:
1038                 return parent_rate / (val + 1);
1039         case K210_DIV_EVEN:
1040                 return parent_rate / 2 / (val + 1);
1041         case K210_DIV_POWER:
1042                 /* This is ACLK, which has no divider on IN0 */
1043                 if (parent == K210_CLK_IN0)
1044                         return parent_rate;
1045                 return parent_rate / (2 << val);
1046         default:
1047                 assert(false);
1048                 return -EINVAL;
1049         };
1050 }
1051
1052 static ulong k210_clk_get_rate(struct clk *clk)
1053 {
1054         return do_k210_clk_get_rate(dev_get_priv(clk->dev), clk->id);
1055 }
1056
1057 static ulong k210_clk_set_rate(struct clk *clk, unsigned long rate)
1058 {
1059         return -ENOSYS;
1060 }
1061
1062 static int do_k210_clk_set_parent(struct k210_clk_priv *priv, int id, int new)
1063 {
1064         int i;
1065         const struct k210_mux_params *mux;
1066
1067         if (!(k210_clks[id].flags & K210_CLKF_MUX))
1068                 return -ENOSYS;
1069         mux = &k210_muxes[k210_clks[id].mux];
1070
1071         for (i = 0; i < mux->num_parents; i++) {
1072                 if (mux->parents[i] == new) {
1073                         k210_clk_writel(priv, mux->off, mux->shift, mux->width,
1074                                         i);
1075                         return 0;
1076                 }
1077         }
1078         return -EINVAL;
1079 }
1080
1081 static int k210_clk_set_parent(struct clk *clk, struct clk *parent)
1082 {
1083         return do_k210_clk_set_parent(dev_get_priv(clk->dev), clk->id,
1084                                       parent->id);
1085 }
1086
1087 static int k210_clk_endisable(struct k210_clk_priv *priv, int id, bool enable)
1088 {
1089         int parent = k210_clk_get_parent(priv, id);
1090         const struct k210_gate_params *gate;
1091
1092         if (id == K210_CLK_IN0) {
1093                 if (enable)
1094                         return clk_enable(&priv->in0);
1095                 else
1096                         return clk_disable(&priv->in0);
1097         }
1098
1099         /* Only recursively enable clocks since we don't track refcounts */
1100         if (enable) {
1101                 int ret = k210_clk_endisable(priv, parent, true);
1102
1103                 if (ret && ret != -ENOSYS)
1104                         return ret;
1105         }
1106
1107         if (k210_clks[id].flags & K210_CLKF_PLL) {
1108                 if (enable)
1109                         return k210_pll_enable(priv, k210_clks[id].pll);
1110                 else
1111                         return k210_pll_disable(priv, k210_clks[id].pll);
1112         }
1113
1114         if (k210_clks[id].gate == K210_CLK_GATE_NONE)
1115                 return -ENOSYS;
1116         gate = &k210_gates[k210_clks[id].gate];
1117
1118         k210_clk_writel(priv, gate->off, gate->bit_idx, 1, enable);
1119         return 0;
1120 }
1121
1122 static int k210_clk_enable(struct clk *clk)
1123 {
1124         return k210_clk_endisable(dev_get_priv(clk->dev), clk->id, true);
1125 }
1126
1127 static int k210_clk_disable(struct clk *clk)
1128 {
1129         return k210_clk_endisable(dev_get_priv(clk->dev), clk->id, false);
1130 }
1131
1132 static int k210_clk_request(struct clk *clk)
1133 {
1134         if (clk->id >= ARRAY_SIZE(k210_clks))
1135                 return -EINVAL;
1136         return 0;
1137 }
1138
1139 static const struct clk_ops k210_clk_ops = {
1140         .request = k210_clk_request,
1141         .set_rate = k210_clk_set_rate,
1142         .get_rate = k210_clk_get_rate,
1143         .set_parent = k210_clk_set_parent,
1144         .enable = k210_clk_enable,
1145         .disable = k210_clk_disable,
1146 };
1147
1148 static int k210_clk_probe(struct udevice *dev)
1149 {
1150         int ret;
1151         struct k210_clk_priv *priv = dev_get_priv(dev);
1152
1153         priv->base = dev_read_addr_ptr(dev_get_parent(dev));
1154         if (!priv->base)
1155                 return -EINVAL;
1156
1157         ret = clk_get_by_index(dev, 0, &priv->in0);
1158         if (ret)
1159                 return ret;
1160
1161         return 0;
1162 }
1163
1164 static const struct udevice_id k210_clk_ids[] = {
1165         { .compatible = "kendryte,k210-clk" },
1166         { },
1167 };
1168
1169 U_BOOT_DRIVER(k210_clk) = {
1170         .name = "k210_clk",
1171         .id = UCLASS_CLK,
1172         .of_match = k210_clk_ids,
1173         .ops = &k210_clk_ops,
1174         .probe = k210_clk_probe,
1175         .priv_auto = sizeof(struct k210_clk_priv),
1176 };