1 // Copyright 2020 Espressif Systems (Shanghai) PTE LTD 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 #include <esp_osal/esp_osal.h> 16 #include "soc/clk_ctrl_os.h" 17 18 #define DELAY_RTC_CLK_SWITCH 5 19 20 static portMUX_TYPE periph_spinlock = portMUX_INITIALIZER_UNLOCKED; 21 22 static uint8_t s_periph_ref_counts = 0; 23 static uint32_t s_rtc_clk_freq = 0; // Frequency of the 8M/256 clock in Hz 24 periph_rtc_dig_clk8m_enable(void)25bool periph_rtc_dig_clk8m_enable(void) 26 { 27 portENTER_CRITICAL(&periph_spinlock); 28 if (s_periph_ref_counts == 0) { 29 rtc_dig_clk8m_enable(); 30 s_rtc_clk_freq = rtc_clk_freq_cal(rtc_clk_cal(RTC_CAL_8MD256, 100)); 31 if (s_rtc_clk_freq == 0) { 32 portEXIT_CRITICAL(&periph_spinlock); 33 return false; 34 } 35 } 36 s_periph_ref_counts++; 37 portEXIT_CRITICAL(&periph_spinlock); 38 return true; 39 } 40 periph_rtc_dig_clk8m_get_freq(void)41uint32_t periph_rtc_dig_clk8m_get_freq(void) 42 { 43 return s_rtc_clk_freq * 256; 44 } 45 periph_rtc_dig_clk8m_disable(void)46void periph_rtc_dig_clk8m_disable(void) 47 { 48 portENTER_CRITICAL(&periph_spinlock); 49 assert(s_periph_ref_counts > 0); 50 s_periph_ref_counts--; 51 if (s_periph_ref_counts == 0) { 52 s_rtc_clk_freq = 0; 53 rtc_dig_clk8m_disable(); 54 } 55 portEXIT_CRITICAL(&periph_spinlock); 56 } 57