1 /*
2 * Copyright (c) 2020 Raspberry Pi (Trading) Ltd.
3 *
4 * SPDX-License-Identifier: BSD-3-Clause
5 */
6
7 // For frequency and PLL definitions etc.
8 #include "hardware/clocks.h"
9 #include "hardware/pll.h"
10 #include "hardware/resets.h"
11
12 /// \tag::pll_init_calculations[]
pll_init(PLL pll,uint refdiv,uint vco_freq,uint post_div1,uint post_div2)13 void pll_init(PLL pll, uint refdiv, uint vco_freq, uint post_div1, uint post_div2) {
14 uint32_t ref_freq = XOSC_HZ / refdiv;
15
16 // Check vco freq is in an acceptable range
17 assert(vco_freq >= PICO_PLL_VCO_MIN_FREQ_HZ && vco_freq <= PICO_PLL_VCO_MAX_FREQ_HZ);
18
19 // What are we multiplying the reference clock by to get the vco freq
20 // (The regs are called div, because you divide the vco output and compare it to the refclk)
21 uint32_t fbdiv = vco_freq / ref_freq;
22 /// \end::pll_init_calculations[]
23
24 // fbdiv
25 assert(fbdiv >= 16 && fbdiv <= 320);
26
27 // Check divider ranges
28 assert((post_div1 >= 1 && post_div1 <= 7) && (post_div2 >= 1 && post_div2 <= 7));
29
30 // post_div1 should be >= post_div2
31 // from appnote page 11
32 // postdiv1 is designed to operate with a higher input frequency than postdiv2
33
34 // Check that reference frequency is no greater than vco / 16
35 assert(ref_freq <= (vco_freq / 16));
36
37 // div1 feeds into div2 so if div1 is 5 and div2 is 2 then you get a divide by 10
38 uint32_t pdiv = (post_div1 << PLL_PRIM_POSTDIV1_LSB) |
39 (post_div2 << PLL_PRIM_POSTDIV2_LSB);
40
41 /// \tag::pll_init_finish[]
42 if ((pll->cs & PLL_CS_LOCK_BITS) &&
43 (refdiv == (pll->cs & PLL_CS_REFDIV_BITS)) &&
44 (fbdiv == (pll->fbdiv_int & PLL_FBDIV_INT_BITS)) &&
45 (pdiv == (pll->prim & (PLL_PRIM_POSTDIV1_BITS | PLL_PRIM_POSTDIV2_BITS)))) {
46 // do not disrupt PLL that is already correctly configured and operating
47 return;
48 }
49
50 reset_unreset_block_num_wait_blocking(PLL_RESET_NUM(pll));
51
52 // Load VCO-related dividers before starting VCO
53 pll->cs = refdiv;
54 pll->fbdiv_int = fbdiv;
55
56 // Turn on PLL
57 uint32_t power = PLL_PWR_PD_BITS | // Main power
58 PLL_PWR_VCOPD_BITS; // VCO Power
59
60 hw_clear_bits(&pll->pwr, power);
61
62 // Wait for PLL to lock
63 while (!(pll->cs & PLL_CS_LOCK_BITS)) tight_loop_contents();
64
65 // Set up post dividers
66 pll->prim = pdiv;
67
68 // Turn on post divider
69 hw_clear_bits(&pll->pwr, PLL_PWR_POSTDIVPD_BITS);
70 /// \end::pll_init_finish[]
71 }
72
pll_deinit(PLL pll)73 void pll_deinit(PLL pll) {
74 // todo: Make sure there are no sources running from this pll?
75 pll->pwr = PLL_PWR_BITS;
76 }
77