1 /*
2  * Copyright (c) 2024 Ambiq Micro Inc.
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <soc.h>
8 
9 #include <zephyr/drivers/interrupt_controller/gic.h>
10 #include <zephyr/kernel.h>
11 #include <zephyr/logging/log.h>
12 #include <zephyr/pm/pm.h>
13 #include <zephyr/init.h>
14 
15 /* ambiq-sdk includes */
16 #include <am_mcu_apollo.h>
17 
18 LOG_MODULE_DECLARE(soc, CONFIG_SOC_LOG_LEVEL);
19 
pm_state_set(enum pm_state state,uint8_t substate_id)20 void pm_state_set(enum pm_state state, uint8_t substate_id)
21 {
22 	ARG_UNUSED(substate_id);
23 
24 	__disable_irq();
25 	__set_BASEPRI(0);
26 
27 	switch (state) {
28 	case PM_STATE_SUSPEND_TO_IDLE:
29 		/* Put ARM core to normal sleep. */
30 		am_hal_sysctrl_sleep(AM_HAL_SYSCTRL_SLEEP_NORMAL);
31 		break;
32 	case PM_STATE_SUSPEND_TO_RAM:
33 		/* Put ARM core to deep sleep. */
34 		/* Cotex-m: power down, register value preserve.*/
35 		/* Cache: power down*/
36 		/* Flash: power down*/
37 		/* Sram: retention*/
38 		am_hal_sysctrl_sleep(AM_HAL_SYSCTRL_SLEEP_DEEP);
39 		break;
40 	default:
41 		LOG_DBG("Unsupported power state %u", state);
42 		break;
43 	}
44 }
45 
46 /**
47  * @brief PM State Exit Post Operations
48  *
49  * For PM_STATE_SUSPEND_TO_IDLE:
50  *   Nothing is needed after soc woken up.
51  *
52  * For PM_STATE_SUSPEND_TO_RAM:
53  *   Flash, cache, sram automatically switch
54  *   to active state on wake up
55  *
56  * @param state PM State
57  * @param substate_id Unused
58  *
59  */
pm_state_exit_post_ops(enum pm_state state,uint8_t substate_id)60 void pm_state_exit_post_ops(enum pm_state state, uint8_t substate_id)
61 {
62 	ARG_UNUSED(substate_id);
63 
64 	__enable_irq();
65 	irq_unlock(0);
66 }
67 
ambiq_power_init(void)68 void ambiq_power_init(void)
69 {
70 	am_hal_pwrctrl_mcu_memory_config_t sMcuMemCfg = {
71 		.eCacheCfg    = AM_HAL_PWRCTRL_CACHE_NONE,
72 		.bRetainCache = true,
73 		.eDTCMCfg     = AM_HAL_PWRCTRL_DTCM_384K,
74 		.eRetainDTCM  = AM_HAL_PWRCTRL_DTCM_384K,
75 		.bEnableNVM0  = true,
76 		.bRetainNVM0  = false
77 	};
78 
79 	am_hal_pwrctrl_sram_memcfg_t sSRAMCfg = {
80 		.eSRAMCfg        = AM_HAL_PWRCTRL_SRAM_ALL,
81 		.eActiveWithMCU	 = AM_HAL_PWRCTRL_SRAM_NONE,
82 		.eActiveWithGFX	 = AM_HAL_PWRCTRL_SRAM_NONE,
83 		.eActiveWithDISP = AM_HAL_PWRCTRL_SRAM_NONE,
84 		.eActiveWithDSP	 = AM_HAL_PWRCTRL_SRAM_NONE,
85 		.eSRAMRetain     = AM_HAL_PWRCTRL_SRAM_ALL
86 	};
87 
88 	am_hal_pwrctrl_dsp_memory_config_t sDSPMemCfg = {
89 		.bEnableICache = false,
90 		.bRetainCache  = false,
91 		.bEnableRAM	   = false,
92 		.bActiveRAM	   = false,
93 		.bRetainRAM	   = false
94 	};
95 
96 	am_hal_pwrctrl_mcu_memory_config(&sMcuMemCfg);
97 	am_hal_pwrctrl_sram_config(&sSRAMCfg);
98 	am_hal_pwrctrl_dsp_memory_config(AM_HAL_DSP0, &sDSPMemCfg);
99 
100 	am_hal_pwrctrl_periph_disable(AM_HAL_PWRCTRL_PERIPH_CRYPTO);
101 }
102