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