1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2020 Sean Anderson <seanga2@gmail.com>
7 /* For DIV_ROUND_DOWN_ULL, defined in linux/kernel.h */
10 #include <kendryte/pll.h>
13 static int dm_test_k210_pll_calc_config(u32 rate, u32 rate_in,
14 struct k210_pll_config *best)
16 u64 f, r, od, max_r, inv_ratio;
17 s64 error, best_error;
21 max_r = min(16ULL, DIV_ROUND_DOWN_ULL(rate_in, 13300000));
22 inv_ratio = DIV_ROUND_CLOSEST_ULL((u64)rate_in << 32, rate);
25 for (r = 1; r <= max_r; r++) {
26 for (f = 1; f <= 64; f++) {
27 for (od = 1; od <= 16; od++) {
28 u64 vco = DIV_ROUND_CLOSEST_ULL(rate_in * f, r);
30 if (vco > 1750000000 || vco < 340000000)
33 error = DIV_ROUND_CLOSEST_ULL(f * inv_ratio,
35 /* The lower 16 bits are spurious */
36 error = abs((error - BIT(32))) >> 16;
37 if (error < best_error) {
47 if (best_error == S64_MAX)
52 static int dm_test_k210_pll_compare(struct k210_pll_config *ours,
53 struct k210_pll_config *theirs)
55 return (u32)ours->f * theirs->r * theirs->od !=
56 (u32)theirs->f * ours->r * ours->od;
59 static int dm_test_k210_pll(struct unit_test_state *uts)
61 struct k210_pll_config ours, theirs;
63 /* General range checks */
64 ut_asserteq(-EINVAL, k210_pll_calc_config(0, 26000000, &theirs));
65 ut_asserteq(-EINVAL, k210_pll_calc_config(390000000, 0, &theirs));
66 ut_asserteq(-EINVAL, k210_pll_calc_config(2000000000, 26000000,
68 ut_asserteq(-EINVAL, k210_pll_calc_config(390000000, 2000000000,
70 ut_asserteq(-EINVAL, k210_pll_calc_config(1500000000, 20000000,
73 /* Verify we get the same output with brute-force */
74 ut_assertok(dm_test_k210_pll_calc_config(390000000, 26000000, &ours));
75 ut_assertok(k210_pll_calc_config(390000000, 26000000, &theirs));
76 ut_assertok(dm_test_k210_pll_compare(&ours, &theirs));
78 ut_assertok(dm_test_k210_pll_calc_config(26000000, 390000000, &ours));
79 ut_assertok(k210_pll_calc_config(26000000, 390000000, &theirs));
80 ut_assertok(dm_test_k210_pll_compare(&ours, &theirs));
82 ut_assertok(dm_test_k210_pll_calc_config(400000000, 26000000, &ours));
83 ut_assertok(k210_pll_calc_config(400000000, 26000000, &theirs));
84 ut_assertok(dm_test_k210_pll_compare(&ours, &theirs));
86 ut_assertok(dm_test_k210_pll_calc_config(27000000, 26000000, &ours));
87 ut_assertok(k210_pll_calc_config(27000000, 26000000, &theirs));
88 ut_assertok(dm_test_k210_pll_compare(&ours, &theirs));
90 ut_assertok(dm_test_k210_pll_calc_config(26000000, 27000000, &ours));
91 ut_assertok(k210_pll_calc_config(26000000, 27000000, &theirs));
92 ut_assertok(dm_test_k210_pll_compare(&ours, &theirs));
96 DM_TEST(dm_test_k210_pll, 0);