clk: k210: Rewrite to remove CCF
[platform/kernel/u-boot.git] / drivers / clk / kendryte / pll.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 <dm.h>
9 /* For DIV_ROUND_DOWN_ULL, defined in linux/kernel.h */
10 #include <div64.h>
11 #include <log.h>
12 #include <serial.h>
13 #include <asm/io.h>
14 #include <dt-bindings/clock/k210-sysctl.h>
15 #include <dt-bindings/mfd/k210-sysctl.h>
16 #include <kendryte/pll.h>
17 #include <linux/bitfield.h>
18 #include <linux/clk-provider.h>
19 #include <linux/delay.h>
20 #include <linux/err.h>
21
22 /**
23  * struct k210_pll_params - K210 PLL parameters
24  * @off: The offset of the PLL from the base sysctl address
25  * @shift: The offset of the LSB of the lock status
26  * @width: The number of bits in the lock status
27  */
28 struct k210_pll_params {
29         u8 off;
30         u8 shift;
31         u8 width;
32 };
33
34 static const struct k210_pll_params k210_plls[] = {
35 #define PLL(_off, _shift, _width) { \
36         .off = (_off), \
37         .shift = (_shift), \
38         .width = (_width), \
39 }
40         [0] = PLL(K210_SYSCTL_PLL0,  0, 2),
41         [1] = PLL(K210_SYSCTL_PLL1,  8, 1),
42         [2] = PLL(K210_SYSCTL_PLL2, 16, 1),
43 #undef PLL
44 };
45
46 #ifdef CONFIG_CLK_K210_SET_RATE
47 int k210_pll_enable(struct k210_clk_priv *priv, int id);
48 int k210_pll_disable(struct k210_clk_priv *priv, int id);
49 ulong k210_pll_get_rate(struct k210_clk_priv *priv, int id, ulong rate_in);
50
51 /*
52  * The PLL included with the Kendryte K210 appears to be a True Circuits, Inc.
53  * General-Purpose PLL. The logical layout of the PLL with internal feedback is
54  * approximately the following:
55  *
56  *  +---------------+
57  *  |reference clock|
58  *  +---------------+
59  *          |
60  *          v
61  *        +--+
62  *        |/r|
63  *        +--+
64  *          |
65  *          v
66  *   +-------------+
67  *   |divided clock|
68  *   +-------------+
69  *          |
70  *          v
71  *  +--------------+
72  *  |phase detector|<---+
73  *  +--------------+    |
74  *          |           |
75  *          v   +--------------+
76  *        +---+ |feedback clock|
77  *        |VCO| +--------------+
78  *        +---+         ^
79  *          |    +--+   |
80  *          +--->|/f|---+
81  *          |    +--+
82  *          v
83  *        +---+
84  *        |/od|
85  *        +---+
86  *          |
87  *          v
88  *       +------+
89  *       |output|
90  *       +------+
91  *
92  * The k210 PLLs have three factors: r, f, and od. Because of the feedback mode,
93  * the effect of the division by f is to multiply the input frequency. The
94  * equation for the output rate is
95  *   rate = (rate_in * f) / (r * od).
96  * Moving knowns to one side of the equation, we get
97  *   rate / rate_in = f / (r * od)
98  * Rearranging slightly,
99  *   abs_error = abs((rate / rate_in) - (f / (r * od))).
100  * To get relative, error, we divide by the expected ratio
101  *   error = abs((rate / rate_in) - (f / (r * od))) / (rate / rate_in).
102  * Simplifying,
103  *   error = abs(1 - f / (r * od)) / (rate / rate_in)
104  *   error = abs(1 - (f * rate_in) / (r * od * rate))
105  * Using the constants ratio = rate / rate_in and inv_ratio = rate_in / rate,
106  *   error = abs((f * inv_ratio) / (r * od) - 1)
107  * This is the error used in evaluating parameters.
108  *
109  * r and od are four bits each, while f is six bits. Because r and od are
110  * multiplied together, instead of the full 256 values possible if both bits
111  * were used fully, there are only 97 distinct products. Combined with f, there
112  * are 6208 theoretical settings for the PLL. However, most of these settings
113  * can be ruled out immediately because they do not have the correct ratio.
114  *
115  * In addition to the constraint of approximating the desired ratio, parameters
116  * must also keep internal pll frequencies within acceptable ranges. The divided
117  * clock's minimum and maximum frequencies have a ratio of around 128.  This
118  * leaves fairly substantial room to work with, especially since the only
119  * affected parameter is r. The VCO's minimum and maximum frequency have a ratio
120  * of 5, which is considerably more restrictive.
121  *
122  * The r and od factors are stored in a table. This is to make it easy to find
123  * the next-largest product. Some products have multiple factorizations, but
124  * only when one factor has at least a 2.5x ratio to the factors of the other
125  * factorization. This is because any smaller ratio would not make a difference
126  * when ensuring the VCO's frequency is within spec.
127  *
128  * Throughout the calculation function, fixed point arithmetic is used. Because
129  * the range of rate and rate_in may be up to 1.75 GHz, or around 2^30, 64-bit
130  * 32.32 fixed-point numbers are used to represent ratios. In general, to
131  * implement division, the numerator is first multiplied by 2^32. This gives a
132  * result where the whole number part is in the upper 32 bits, and the fraction
133  * is in the lower 32 bits.
134  *
135  * In general, rounding is done to the closest integer. This helps find the best
136  * approximation for the ratio. Rounding in one direction (e.g down) could cause
137  * the function to miss a better ratio with one of the parameters increased by
138  * one.
139  */
140
141 /*
142  * The factors table was generated with the following python code:
143  *
144  * def p(x, y):
145  *    return (1.0*x/y > 2.5) or (1.0*y/x > 2.5)
146  *
147  * factors = {}
148  * for i in range(1, 17):
149  *    for j in range(1, 17):
150  *       fs = factors.get(i*j) or []
151  *       if fs == [] or all([
152  *             (p(i, x) and p(i, y)) or (p(j, x) and p(j, y))
153  *             for (x, y) in fs]):
154  *          fs.append((i, j))
155  *          factors[i*j] = fs
156  *
157  * for k, l in sorted(factors.items()):
158  *    for v in l:
159  *       print("PACK(%s, %s)," % v)
160  */
161 #define PACK(r, od) (((((r) - 1) & 0xF) << 4) | (((od) - 1) & 0xF))
162 #define UNPACK_R(val) ((((val) >> 4) & 0xF) + 1)
163 #define UNPACK_OD(val) (((val) & 0xF) + 1)
164 static const u8 factors[] = {
165         PACK(1, 1),
166         PACK(1, 2),
167         PACK(1, 3),
168         PACK(1, 4),
169         PACK(1, 5),
170         PACK(1, 6),
171         PACK(1, 7),
172         PACK(1, 8),
173         PACK(1, 9),
174         PACK(3, 3),
175         PACK(1, 10),
176         PACK(1, 11),
177         PACK(1, 12),
178         PACK(3, 4),
179         PACK(1, 13),
180         PACK(1, 14),
181         PACK(1, 15),
182         PACK(3, 5),
183         PACK(1, 16),
184         PACK(4, 4),
185         PACK(2, 9),
186         PACK(2, 10),
187         PACK(3, 7),
188         PACK(2, 11),
189         PACK(2, 12),
190         PACK(5, 5),
191         PACK(2, 13),
192         PACK(3, 9),
193         PACK(2, 14),
194         PACK(2, 15),
195         PACK(2, 16),
196         PACK(3, 11),
197         PACK(5, 7),
198         PACK(3, 12),
199         PACK(3, 13),
200         PACK(4, 10),
201         PACK(3, 14),
202         PACK(4, 11),
203         PACK(3, 15),
204         PACK(3, 16),
205         PACK(7, 7),
206         PACK(5, 10),
207         PACK(4, 13),
208         PACK(6, 9),
209         PACK(5, 11),
210         PACK(4, 14),
211         PACK(4, 15),
212         PACK(7, 9),
213         PACK(4, 16),
214         PACK(5, 13),
215         PACK(6, 11),
216         PACK(5, 14),
217         PACK(6, 12),
218         PACK(5, 15),
219         PACK(7, 11),
220         PACK(6, 13),
221         PACK(5, 16),
222         PACK(9, 9),
223         PACK(6, 14),
224         PACK(8, 11),
225         PACK(6, 15),
226         PACK(7, 13),
227         PACK(6, 16),
228         PACK(7, 14),
229         PACK(9, 11),
230         PACK(10, 10),
231         PACK(8, 13),
232         PACK(7, 15),
233         PACK(9, 12),
234         PACK(10, 11),
235         PACK(7, 16),
236         PACK(9, 13),
237         PACK(8, 15),
238         PACK(11, 11),
239         PACK(9, 14),
240         PACK(8, 16),
241         PACK(10, 13),
242         PACK(11, 12),
243         PACK(9, 15),
244         PACK(10, 14),
245         PACK(11, 13),
246         PACK(9, 16),
247         PACK(10, 15),
248         PACK(11, 14),
249         PACK(12, 13),
250         PACK(10, 16),
251         PACK(11, 15),
252         PACK(12, 14),
253         PACK(13, 13),
254         PACK(11, 16),
255         PACK(12, 15),
256         PACK(13, 14),
257         PACK(12, 16),
258         PACK(13, 15),
259         PACK(14, 14),
260         PACK(13, 16),
261         PACK(14, 15),
262         PACK(14, 16),
263         PACK(15, 15),
264         PACK(15, 16),
265         PACK(16, 16),
266 };
267
268 TEST_STATIC int k210_pll_calc_config(u32 rate, u32 rate_in,
269                                      struct k210_pll_config *best)
270 {
271         int i;
272         s64 error, best_error;
273         u64 ratio, inv_ratio; /* fixed point 32.32 ratio of the rates */
274         u64 max_r;
275         u64 r, f, od;
276
277         /*
278          * Can't go over 1.75 GHz or under 21.25 MHz due to limitations on the
279          * VCO frequency. These are not the same limits as below because od can
280          * reduce the output frequency by 16.
281          */
282         if (rate > 1750000000 || rate < 21250000)
283                 return -EINVAL;
284
285         /* Similar restrictions on the input rate */
286         if (rate_in > 1750000000 || rate_in < 13300000)
287                 return -EINVAL;
288
289         ratio = DIV_ROUND_CLOSEST_ULL((u64)rate << 32, rate_in);
290         inv_ratio = DIV_ROUND_CLOSEST_ULL((u64)rate_in << 32, rate);
291         /* Can't increase by more than 64 or reduce by more than 256 */
292         if (rate > rate_in && ratio > (64ULL << 32))
293                 return -EINVAL;
294         else if (rate <= rate_in && inv_ratio > (256ULL << 32))
295                 return -EINVAL;
296
297         /*
298          * The divided clock (rate_in / r) must stay between 1.75 GHz and 13.3
299          * MHz. There is no minimum, since the only way to get a higher input
300          * clock than 26 MHz is to use a clock generated by a PLL. Because PLLs
301          * cannot output frequencies greater than 1.75 GHz, the minimum would
302          * never be greater than one.
303          */
304         max_r = DIV_ROUND_DOWN_ULL(rate_in, 13300000);
305
306         /* Variables get immediately incremented, so start at -1th iteration */
307         i = -1;
308         f = 0;
309         r = 0;
310         od = 0;
311         best_error = S64_MAX;
312         error = best_error;
313         /* do-while here so we always try at least one ratio */
314         do {
315                 /*
316                  * Whether we swapped r and od while enforcing frequency limits
317                  */
318                 bool swapped = false;
319                 u64 last_od = od;
320                 u64 last_r = r;
321
322                 /*
323                  * Try the next largest value for f (or r and od) and
324                  * recalculate the other parameters based on that
325                  */
326                 if (rate > rate_in) {
327                         /*
328                          * Skip factors of the same product if we already tried
329                          * out that product
330                          */
331                         do {
332                                 i++;
333                                 r = UNPACK_R(factors[i]);
334                                 od = UNPACK_OD(factors[i]);
335                         } while (i + 1 < ARRAY_SIZE(factors) &&
336                                  r * od == last_r * last_od);
337
338                         /* Round close */
339                         f = (r * od * ratio + BIT(31)) >> 32;
340                         if (f > 64)
341                                 f = 64;
342                 } else {
343                         u64 tmp = ++f * inv_ratio;
344                         bool round_up = !!(tmp & BIT(31));
345                         u32 goal = (tmp >> 32) + round_up;
346                         u32 err, last_err;
347
348                         /* Get the next r/od pair in factors */
349                         while (r * od < goal && i + 1 < ARRAY_SIZE(factors)) {
350                                 i++;
351                                 r = UNPACK_R(factors[i]);
352                                 od = UNPACK_OD(factors[i]);
353                         }
354
355                         /*
356                          * This is a case of double rounding. If we rounded up
357                          * above, we need to round down (in cases of ties) here.
358                          * This prevents off-by-one errors resulting from
359                          * choosing X+2 over X when X.Y rounds up to X+1 and
360                          * there is no r * od = X+1. For the converse, when X.Y
361                          * is rounded down to X, we should choose X+1 over X-1.
362                          */
363                         err = abs(r * od - goal);
364                         last_err = abs(last_r * last_od - goal);
365                         if (last_err < err || (round_up && last_err == err)) {
366                                 i--;
367                                 r = last_r;
368                                 od = last_od;
369                         }
370                 }
371
372                 /*
373                  * Enforce limits on internal clock frequencies. If we
374                  * aren't in spec, try swapping r and od. If everything is
375                  * in-spec, calculate the relative error.
376                  */
377                 while (true) {
378                         /*
379                          * Whether the intermediate frequencies are out-of-spec
380                          */
381                         bool out_of_spec = false;
382
383                         if (r > max_r) {
384                                 out_of_spec = true;
385                         } else {
386                                 /*
387                                  * There is no way to only divide once; we need
388                                  * to examine the frequency with and without the
389                                  * effect of od.
390                                  */
391                                 u64 vco = DIV_ROUND_CLOSEST_ULL(rate_in * f, r);
392
393                                 if (vco > 1750000000 || vco < 340000000)
394                                         out_of_spec = true;
395                         }
396
397                         if (out_of_spec) {
398                                 if (!swapped) {
399                                         u64 tmp = r;
400
401                                         r = od;
402                                         od = tmp;
403                                         swapped = true;
404                                         continue;
405                                 } else {
406                                         /*
407                                          * Try looking ahead to see if there are
408                                          * additional factors for the same
409                                          * product.
410                                          */
411                                         if (i + 1 < ARRAY_SIZE(factors)) {
412                                                 u64 new_r, new_od;
413
414                                                 i++;
415                                                 new_r = UNPACK_R(factors[i]);
416                                                 new_od = UNPACK_OD(factors[i]);
417                                                 if (r * od == new_r * new_od) {
418                                                         r = new_r;
419                                                         od = new_od;
420                                                         swapped = false;
421                                                         continue;
422                                                 }
423                                                 i--;
424                                         }
425                                         break;
426                                 }
427                         }
428
429                         error = DIV_ROUND_CLOSEST_ULL(f * inv_ratio, r * od);
430                         /* The lower 16 bits are spurious */
431                         error = abs((error - BIT(32))) >> 16;
432
433                         if (error < best_error) {
434                                 best->r = r;
435                                 best->f = f;
436                                 best->od = od;
437                                 best_error = error;
438                         }
439                         break;
440                 }
441         } while (f < 64 && i + 1 < ARRAY_SIZE(factors) && error != 0);
442
443         if (best_error == S64_MAX)
444                 return -EINVAL;
445
446         log_debug("best error %lld\n", best_error);
447         return 0;
448 }
449
450 static ulong k210_pll_set_rate(struct k210_clk_priv *priv, int id, ulong rate,
451                                ulong rate_in)
452 {
453         int err;
454         const struct k210_pll_params *pll = &k210_plls[id];
455         struct k210_pll_config config = {};
456         u32 reg;
457
458         if (rate_in < 0)
459                 return rate_in;
460
461         log_debug("Calculating parameters with rate=%lu and rate_in=%lld\n",
462                   rate, rate_in);
463         err = k210_pll_calc_config(rate, rate_in, &config);
464         if (err)
465                 return err;
466         log_debug("Got r=%u f=%u od=%u\n", config.r, config.f, config.od);
467
468         /*
469          * Don't use clk_disable as it might not actually disable the pll due to
470          * refcounting
471          */
472         k210_pll_disable(clk);
473
474         reg = readl(priv->base + pll->off);
475         reg &= ~K210_PLL_CLKR
476             &  ~K210_PLL_CLKF
477             &  ~K210_PLL_CLKOD
478             &  ~K210_PLL_BWADJ;
479         reg |= FIELD_PREP(K210_PLL_CLKR, config.r - 1)
480             |  FIELD_PREP(K210_PLL_CLKF, config.f - 1)
481             |  FIELD_PREP(K210_PLL_CLKOD, config.od - 1)
482             |  FIELD_PREP(K210_PLL_BWADJ, config.f - 1);
483         writel(reg, priv->base + pll->off);
484
485         err = k210_pll_enable(clk);
486         if (err)
487                 return err;
488
489         serial_setbrg();
490         return clk_get_rate(clk);
491 }
492 #else
493 ulong k210_pll_set_rate(struct k210_clk_priv *priv, int id, ulong rate,
494                         ulong rate_in)
495 {
496         return -ENOSYS;
497 }
498 #endif /* CONFIG_CLK_K210_SET_RATE */
499
500 ulong k210_pll_get_rate(struct k210_clk_priv *priv, int id, ulong rate_in)
501 {
502         u64 r, f, od;
503         u32 reg = readl(priv->base + k210_plls[id].off);
504
505         if (rate_in < 0 || (reg & K210_PLL_BYPASS))
506                 return rate_in;
507
508         if (!(reg & K210_PLL_PWRD))
509                 return 0;
510
511         r = FIELD_GET(K210_PLL_CLKR, reg) + 1;
512         f = FIELD_GET(K210_PLL_CLKF, reg) + 1;
513         od = FIELD_GET(K210_PLL_CLKOD, reg) + 1;
514
515         return DIV_ROUND_DOWN_ULL(((u64)rate_in) * f, r * od);
516 }
517
518 /*
519  * Wait for the PLL to be locked. If the PLL is not locked, try clearing the
520  * slip before retrying
521  */
522 void k210_pll_waitfor_lock(struct k210_clk_priv *priv, int id)
523 {
524         const struct k210_pll_params *pll = &k210_plls[id];
525         u32 mask = GENMASK(pll->width - 1, 0) << pll->shift;
526
527         while (true) {
528                 u32 reg = readl(priv->base + K210_SYSCTL_PLL_LOCK);
529
530                 if ((reg & mask) == mask)
531                         break;
532
533                 reg |= BIT(pll->shift + K210_PLL_CLEAR_SLIP);
534                 writel(reg, priv->base + K210_SYSCTL_PLL_LOCK);
535         }
536 }
537
538 /* Adapted from sysctl_pll_enable */
539 int k210_pll_enable(struct k210_clk_priv *priv, int id)
540 {
541         const struct k210_pll_params *pll = &k210_plls[id];
542         u32 reg = readl(priv->base + pll->off);
543
544         if ((reg & K210_PLL_PWRD) && (reg & K210_PLL_EN) &&
545             !(reg & K210_PLL_RESET))
546                 return 0;
547
548         reg |= K210_PLL_PWRD;
549         writel(reg, priv->base + pll->off);
550
551         /* Ensure reset is low before asserting it */
552         reg &= ~K210_PLL_RESET;
553         writel(reg, priv->base + pll->off);
554         reg |= K210_PLL_RESET;
555         writel(reg, priv->base + pll->off);
556         nop();
557         nop();
558         reg &= ~K210_PLL_RESET;
559         writel(reg, priv->base + pll->off);
560
561         k210_pll_waitfor_lock(priv, id);
562
563         reg &= ~K210_PLL_BYPASS;
564         reg |= K210_PLL_EN;
565         writel(reg, priv->base + pll->off);
566
567         return 0;
568 }
569
570 int k210_pll_disable(struct k210_clk_priv *priv, int id)
571 {
572         const struct k210_pll_params *pll = &k210_plls[id];
573         u32 reg = readl(priv->base + pll->off);
574
575         /*
576          * Bypassing before powering off is important so child clocks don't stop
577          * working. This is especially important for pll0, the indirect parent
578          * of the cpu clock.
579          */
580         reg |= K210_PLL_BYPASS;
581         writel(reg, priv->base + pll->off);
582
583         reg &= ~K210_PLL_PWRD;
584         reg &= ~K210_PLL_EN;
585         writel(reg, priv->base + pll->off);
586         return 0;
587 }