1 /*
2 * Copyright (c) 2017, NXP
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include <zephyr/kernel.h>
8 #include <zephyr/device.h>
9 #include <zephyr/init.h>
10 #include <soc.h>
11 #include <zephyr/drivers/uart.h>
12 #include <fsl_common.h>
13 #include <fsl_clock.h>
14
15 #define LPUART0SRC_OSCERCLK (1)
16 #define TPMSRC_MCGPLLCLK (1)
17
18 #define CLOCK_NODEID(clk) \
19 DT_CHILD(DT_INST(0, nxp_kinetis_sim), clk)
20
21 #define CLOCK_DIVIDER(clk) \
22 DT_PROP_OR(CLOCK_NODEID(clk), clock_div, 1) - 1
23
24 static const osc_config_t oscConfig = {
25 .freq = CONFIG_OSC_XTAL0_FREQ,
26
27 #if defined(CONFIG_OSC_EXTERNAL)
28 .workMode = kOSC_ModeExt,
29 #elif defined(CONFIG_OSC_LOW_POWER)
30 .workMode = kOSC_ModeOscLowPower,
31 #elif defined(CONFIG_OSC_HIGH_GAIN)
32 .workMode = kOSC_ModeOscHighGain,
33 #else
34 #error "An oscillator mode must be defined"
35 #endif
36 };
37
38 static const sim_clock_config_t simConfig = {
39 .er32kSrc = DT_PROP(DT_INST(0, nxp_kinetis_sim), er32k_select),
40 .clkdiv1 = SIM_CLKDIV1_OUTDIV1(CLOCK_DIVIDER(core_clk)) |
41 SIM_CLKDIV1_OUTDIV4(CLOCK_DIVIDER(flash_clk)),
42 };
43
44 /* This function comes from the MCUX SDK:
45 * modules/hal/nxp/mcux/devices/MKW41Z4/clock_config.c
46 */
CLOCK_SYS_FllStableDelay(void)47 static void CLOCK_SYS_FllStableDelay(void)
48 {
49 uint32_t i = 30000U;
50 while (i--) {
51 __NOP();
52 }
53 }
54
clock_init(void)55 static ALWAYS_INLINE void clock_init(void)
56 {
57 CLOCK_SetSimSafeDivs();
58
59 CLOCK_InitOsc0(&oscConfig);
60 CLOCK_SetXtal0Freq(CONFIG_OSC_XTAL0_FREQ);
61
62 CLOCK_BootToFeeMode(kMCG_OscselOsc, CONFIG_MCG_FRDIV, kMCG_Dmx32Default,
63 kMCG_DrsMid, CLOCK_SYS_FllStableDelay);
64
65 CLOCK_SetInternalRefClkConfig(kMCG_IrclkEnable, kMCG_IrcSlow,
66 CONFIG_MCG_FCRDIV);
67
68 CLOCK_SetSimConfig(&simConfig);
69
70 #if DT_NODE_HAS_STATUS(DT_NODELABEL(lpuart0), okay)
71 CLOCK_SetLpuartClock(LPUART0SRC_OSCERCLK);
72 #endif
73
74 #if defined(CONFIG_PWM) && \
75 (DT_NODE_HAS_STATUS(DT_NODELABEL(pwm0), okay) || \
76 DT_NODE_HAS_STATUS(DT_NODELABEL(pwm1), okay) || \
77 DT_NODE_HAS_STATUS(DT_NODELABEL(pwm2), okay))
78 CLOCK_SetTpmClock(TPMSRC_MCGPLLCLK);
79 #endif
80 }
81
kwx_init(void)82 static int kwx_init(void)
83 {
84 /* Initialize system clock to 40 MHz */
85 clock_init();
86
87 return 0;
88 }
89
90 #ifdef CONFIG_PLATFORM_SPECIFIC_INIT
91
z_arm_platform_init(void)92 void z_arm_platform_init(void)
93 {
94 SystemInit();
95 }
96
97 #endif /* CONFIG_PLATFORM_SPECIFIC_INIT */
98
99 SYS_INIT(kwx_init, PRE_KERNEL_1, 0);
100