Merge branch 'refactor/timekeeping_init' into 'master'

Timekeeping refactor

Closes IDF-1864

See merge request espressif/esp-idf!7824
This commit is contained in:
Angus Gratton 2020-08-17 08:13:44 +08:00
commit 62c4b569ad
25 changed files with 546 additions and 275 deletions

View File

@ -0,0 +1,39 @@
// Copyright 2015-2017 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @file esp32/rtc.h
*
* This file contains declarations of rtc related functions.
*/
/**
* @brief Get current value of RTC counter in microseconds
*
* Note: this function may take up to 1 RTC_SLOW_CLK cycle to execute
*
* @return current value of RTC counter in microseconds
*/
uint64_t esp_rtc_get_time_us(void);
#ifdef __cplusplus
}
#endif

View File

@ -0,0 +1,39 @@
// Copyright 2015-2017 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @file esp32s2/rtc.h
*
* This file contains declarations of rtc related functions.
*/
/**
* @brief Get current value of RTC counter in microseconds
*
* Note: this function may take up to 1 RTC_SLOW_CLK cycle to execute
*
* @return current value of RTC counter in microseconds
*/
uint64_t esp_rtc_get_time_us(void);
#ifdef __cplusplus
}
#endif

View File

@ -61,6 +61,21 @@ void esp_reset_reason_set_hint(esp_reset_reason_t hint);
*/
esp_reset_reason_t esp_reset_reason_get_hint(void);
/**
* @brief Get the time in microseconds since startup
*
* @returns time since startup in microseconds
*/
int64_t esp_system_get_time(void);
/**
* @brief Get the resolution of the time returned by `esp_system_get_time`.
*
* @returns the resolution in microseconds
*/
uint32_t esp_system_get_time_resolution(void);
#ifdef __cplusplus
}
#endif

View File

@ -1,4 +1,4 @@
idf_component_register(SRCS "panic.c" "system_api.c" "startup.c"
idf_component_register(SRCS "panic.c" "system_api.c" "startup.c" "system_time.c"
INCLUDE_DIRS include
PRIV_REQUIRES spi_flash app_update
# requirements due to startup code
@ -21,4 +21,4 @@ endif()
set_source_files_properties(
startup.c
PROPERTIES COMPILE_FLAGS
-fno-stack-protector)
-fno-stack-protector)

View File

@ -64,6 +64,10 @@ static __attribute__((used)) esp_system_init_fn_t _SECTION_ATTR_IMPL(".esp_syste
static __attribute__((used)) __VA_ARGS__ void __esp_system_init_fn_##f(void) // [refactor-todo] this can be made public API if we allow components to declare init functions,
// instead of calling them explicitly
extern uint64_t g_startup_time; // Startup time that serves as the point of origin for system time. Should be set by the entry
// function in the port layer. May be 0 as well if this is not backed by a persistent counter, in which case
// startup time = system time = 0 at the point the entry function sets this variable.
#ifdef __cplusplus
}
#endif

View File

@ -286,6 +286,7 @@ typedef struct {
*/
void esp_chip_info(esp_chip_info_t* out_info);
#if CONFIG_ESP32_ECO3_CACHE_LOCK_FIX
/**
* @brief Cache lock bug exists or not

View File

@ -30,11 +30,13 @@
#include "sdkconfig.h"
#if CONFIG_IDF_TARGET_ESP32
#include "esp32/rtc.h"
#include "esp32/cache_err_int.h"
#include "esp32/rom/cache.h"
#include "esp32/rom/rtc.h"
#include "esp32/spiram.h"
#elif CONFIG_IDF_TARGET_ESP32S2
#include "esp32s2/rtc.h"
#include "esp32s2/brownout.h"
#include "esp32s2/cache_err_int.h"
#include "esp32s2/rom/cache.h"
@ -54,6 +56,8 @@
#include "soc/dport_reg.h"
#include "soc/efuse_reg.h"
#include "soc/cpu.h"
#include "soc/rtc.h"
#include "soc/spinlock.h"
#include "trax.h"
@ -66,6 +70,7 @@
#endif
#include "esp_private/startup_internal.h"
#include "esp_private/system_internal.h"
extern int _bss_start;
extern int _bss_end;
@ -103,7 +108,6 @@ void startup_resume_other_cores(void)
s_resume_cores = true;
}
void IRAM_ATTR call_start_cpu1(void)
{
cpu_hal_set_vecbase(&_init_start);
@ -356,6 +360,11 @@ void IRAM_ATTR call_start_cpu0(void)
esp_clk_init();
esp_perip_clk_init();
// Now that the clocks have been set-up, set the startup time from RTC
// and default RTC-backed system time provider.
g_startup_time = esp_rtc_get_time_us();
intr_matrix_clear();
#ifdef CONFIG_ESP_CONSOLE_UART

View File

@ -78,6 +78,8 @@
#define STRINGIFY(s) STRINGIFY2(s)
#define STRINGIFY2(s) #s
uint64_t g_startup_time = 0;
// App entry point for core 0
extern void start_app(void);
@ -183,6 +185,7 @@ static void IRAM_ATTR do_core_init(void)
fail initializing it properly. */
heap_caps_init();
esp_setup_syscall_table();
esp_newlib_time_init();
if (g_spiram_ok) {
#if CONFIG_SPIRAM_BOOT_INIT && (CONFIG_SPIRAM_USE_CAPS_ALLOC || CONFIG_SPIRAM_USE_MALLOC)
@ -244,9 +247,6 @@ static void IRAM_ATTR do_core_init(void)
esp_efuse_disable_basic_rom_console();
#endif
esp_timer_init();
esp_set_time_from_rtc();
// [refactor-todo] move this to secondary init
#if CONFIG_APPTRACE_ENABLE
err = esp_apptrace_init();
@ -301,6 +301,7 @@ static void IRAM_ATTR do_secondary_init(void)
void IRAM_ATTR start_cpu0_default(void)
{
ESP_EARLY_LOGI(TAG, "Pro cpu start user code");
// Display information about the current running image.
@ -353,6 +354,8 @@ void IRAM_ATTR start_cpu0_default(void)
IRAM_ATTR ESP_SYSTEM_INIT_FN(init_components0, BIT(0))
{
esp_timer_init();
#if defined(CONFIG_PM_ENABLE) && defined(CONFIG_ESP_CONSOLE_UART)
/* When DFS is enabled, use REFTICK as UART clock source */
uart_ll_set_baudrate(UART_LL_GET_HW(CONFIG_ESP_CONSOLE_UART_NUM), UART_SCLK_REF_TICK, CONFIG_ESP_CONSOLE_UART_BAUDRATE);

View File

@ -0,0 +1,46 @@
// Copyright 2020 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "esp_system.h"
#include "esp_attr.h"
#include "soc/spinlock.h"
#include "soc/rtc.h"
#include "sdkconfig.h"
#if CONFIG_IDF_TARGET_ESP32
#include "esp32/rtc.h"
#elif CONFIG_IDF_TARGET_ESP32S2
#include "esp32s2/rtc.h"
#endif
#include "esp_private/startup_internal.h"
// A component in the build should provide strong implementations that make use of
// and actual hardware timer to provide timekeeping functions.
int64_t IRAM_ATTR __attribute__((weak)) esp_system_get_time(void)
{
int64_t t = 0;
static spinlock_t s_time_lock = SPINLOCK_INITIALIZER;
spinlock_acquire(&s_time_lock, SPINLOCK_WAIT_FOREVER);
t = (esp_rtc_get_time_us() - g_startup_time);
spinlock_release(&s_time_lock);
return t;
}
uint32_t IRAM_ATTR __attribute__((weak)) esp_system_get_time_resolution(void)
{
return 1000000L / rtc_clk_slow_freq_get_hz();
}

View File

@ -1,7 +1,7 @@
idf_build_get_property(target IDF_TARGET)
set(srcs "src/esp_timer.c"
"src/ets_timer_legacy.c")
set(srcs "src/esp_timer.c"
"src/ets_timer_legacy.c")
if(CONFIG_ESP_TIMER_IMPL_FRC2)
list(APPEND srcs "src/esp_timer_impl_frc_legacy.c")

View File

@ -24,10 +24,28 @@
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "freertos/xtensa_api.h"
#include "soc/spinlock.h"
#include "esp_timer.h"
#include "esp_timer_impl.h"
#include "esp_private/startup_internal.h"
#include "esp_private/esp_timer_private.h"
#include "esp_private/system_internal.h"
#if CONFIG_IDF_TARGET_ESP32
#include "esp32/rtc.h"
#elif CONFIG_IDF_TARGET_ESP32S2
#include "esp32s2/rtc.h"
#endif
#include "sdkconfig.h"
#if defined( CONFIG_ESP32_TIME_SYSCALL_USE_FRC1 ) || \
defined( CONFIG_ESP32_TIME_SYSCALL_USE_RTC_FRC1 ) || \
defined( CONFIG_ESP32S2_TIME_SYSCALL_USE_FRC1 ) || \
defined( CONFIG_ESP32S2_TIME_SYSCALL_USE_RTC_FRC1 )
#define WITH_FRC 1
#endif
#ifdef CONFIG_ESP_TIMER_PROFILING
#define WITH_PROFILING 1
@ -97,7 +115,6 @@ static StaticQueue_t s_timer_semaphore_memory;
static portMUX_TYPE s_timer_lock = portMUX_INITIALIZER_UNLOCKED;
esp_err_t esp_timer_create(const esp_timer_create_args_t* args,
esp_timer_handle_t* out_handle)
{
@ -349,7 +366,6 @@ static IRAM_ATTR bool is_initialized(void)
return s_timer_task != NULL;
}
esp_err_t esp_timer_init(void)
{
esp_err_t err;
@ -380,6 +396,12 @@ esp_err_t esp_timer_init(void)
goto out;
}
#if WITH_FRC
// [refactor-todo] this logic, "esp_rtc_get_time_us() - g_startup_time", is also
// the weak definition of esp_system_get_time; find a way to remove this duplication.
esp_timer_private_advance(esp_rtc_get_time_us() - g_startup_time);
#endif
return ESP_OK;
out:
@ -506,3 +528,26 @@ int64_t IRAM_ATTR esp_timer_get_next_alarm(void)
timer_list_unlock();
return next_alarm;
}
int64_t IRAM_ATTR esp_timer_get_time(void)
{
if(is_initialized()) {
return esp_timer_impl_get_time();
} else {
return 0;
}
}
// Provides strong definition for system time functions relied upon
// by core components.
#if WITH_FRC
int64_t IRAM_ATTR esp_system_get_time(void)
{
return esp_timer_get_time();
}
uint32_t IRAM_ATTR esp_system_get_time_resolution(void)
{
return 1;
}
#endif

View File

@ -209,8 +209,6 @@ int64_t IRAM_ATTR esp_timer_impl_get_time(void)
return result;
}
int64_t esp_timer_get_time(void) __attribute__((alias("esp_timer_impl_get_time")));
void IRAM_ATTR esp_timer_impl_set_alarm(uint64_t timestamp)
{
portENTER_CRITICAL_SAFE(&s_time_update_lock);

View File

@ -149,8 +149,6 @@ int64_t IRAM_ATTR esp_timer_impl_get_time(void)
return esp_timer_impl_get_counter_reg() / TICKS_PER_US;
}
int64_t esp_timer_get_time(void) __attribute__((alias("esp_timer_impl_get_time")));
void IRAM_ATTR esp_timer_impl_set_alarm(uint64_t timestamp)
{
portENTER_CRITICAL_SAFE(&s_time_update_lock);

View File

@ -68,9 +68,6 @@ int64_t IRAM_ATTR esp_timer_impl_get_time(void)
return systimer_hal_get_time(SYSTIMER_COUNTER_0);
}
// Xtensa architecture doesn't have tail call optimization, using alias here can improve performance somehow
int64_t esp_timer_get_time(void) __attribute__((alias("esp_timer_impl_get_time")));
void IRAM_ATTR esp_timer_impl_set_alarm(uint64_t timestamp)
{
portENTER_CRITICAL_SAFE(&s_time_update_lock);

View File

@ -20,7 +20,8 @@ list(APPEND ldfragments newlib.lf)
idf_component_register(SRCS "${srcs}"
INCLUDE_DIRS "${include_dirs}"
PRIV_REQUIRES soc esp_timer
PRIV_INCLUDE_DIRS priv_include
PRIV_REQUIRES soc
LDFRAGMENTS "${ldfragments}")
# Toolchain libraries require code defined in this component
@ -40,3 +41,5 @@ target_link_libraries(${COMPONENT_LIB} INTERFACE "${EXTRA_LINK_FLAGS}")
if(CONFIG_NEWLIB_NANO_FORMAT)
target_link_libraries(${COMPONENT_LIB} INTERFACE "--specs=nano.specs")
endif()
add_subdirectory(port)

View File

@ -12,6 +12,9 @@ ifdef CONFIG_SPIRAM_CACHE_WORKAROUND
COMPONENT_ADD_LDFRAGMENTS := esp32-spiram-rom-functions-c.lf
endif
COMPONENT_PRIV_INCLUDEDIRS := priv_include
COMPONENT_SRCDIRS := . port
# Forces the linker to include locks, heap, and syscalls from this component,
# instead of the implementations provided by newlib.
COMPONENT_ADD_LDFLAGS += -u newlib_include_locks_impl

View File

@ -17,6 +17,11 @@
#include <sys/reent.h>
/*
* Initialize newlib time functions
*/
void esp_newlib_time_init(void);
/**
* Replacement for newlib's _REENT_INIT_PTR and __sinit.
*

View File

@ -0,0 +1 @@
target_sources(${COMPONENT_LIB} PRIVATE "${CMAKE_CURRENT_LIST_DIR}/esp_time_impl.c")

View File

@ -0,0 +1,203 @@
// Copyright 2020 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <stdint.h>
#include <time.h>
#include <sys/time.h>
#include "esp_system.h"
#include "soc/spinlock.h"
#include "soc/rtc.h"
#include "esp_rom_sys.h"
#include "esp_private/system_internal.h"
#include "esp_time_impl.h"
#include "sdkconfig.h"
#if CONFIG_IDF_TARGET_ESP32
#include "esp32/rom/rtc.h"
#include "esp32/clk.h"
#include "esp32/rtc.h"
#elif CONFIG_IDF_TARGET_ESP32S2
#include "esp32s2/rom/rtc.h"
#include "esp32s2/clk.h"
#include "esp32s2/rtc.h"
#endif
#if defined( CONFIG_ESP32_TIME_SYSCALL_USE_RTC ) \
|| defined( CONFIG_ESP32_TIME_SYSCALL_USE_RTC_FRC1 ) \
|| defined( CONFIG_ESP32S2_TIME_SYSCALL_USE_RTC ) \
|| defined( CONFIG_ESP32S2_TIME_SYSCALL_USE_RTC_FRC1 )
#define WITH_RTC 1
#endif
#if defined( CONFIG_ESP32_TIME_SYSCALL_USE_FRC1 ) \
|| defined( CONFIG_ESP32_TIME_SYSCALL_USE_RTC_FRC1 ) \
|| defined( CONFIG_ESP32S2_TIME_SYSCALL_USE_FRC1 ) \
|| defined( CONFIG_ESP32S2_TIME_SYSCALL_USE_RTC_FRC1 )
#define WITH_FRC 1
#endif
// Offset between FRC timer and the RTC.
// Initialized after reset or light sleep.
#if defined(WITH_RTC) && defined(WITH_FRC)
uint64_t s_microseconds_offset;
#endif
#ifndef WITH_RTC
static uint64_t s_boot_time; // when RTC is used to persist time, two RTC_STORE registers are used to store boot time instead
#endif
static spinlock_t s_time_lock = SPINLOCK_INITIALIZER;
#if defined( WITH_FRC ) || defined( WITH_RTC )
uint64_t esp_time_impl_get_time_since_boot(void)
{
uint64_t microseconds = 0;
#ifdef WITH_FRC
#ifdef WITH_RTC
microseconds = s_microseconds_offset + esp_system_get_time();
#else
microseconds = esp_system_get_time();
#endif // WITH_RTC
#elif defined(WITH_RTC)
spinlock_acquire(&s_time_lock, SPINLOCK_WAIT_FOREVER);
microseconds = esp_rtc_get_time_us();
spinlock_release(&s_time_lock);
#endif // WITH_FRC
return microseconds;
}
uint64_t esp_time_impl_get_time(void)
{
uint64_t microseconds = 0;
#if defined( WITH_FRC )
microseconds = esp_system_get_time();
#elif defined( WITH_RTC )
spinlock_acquire(&s_time_lock, SPINLOCK_WAIT_FOREVER);
microseconds = esp_rtc_get_time_us();
spinlock_release(&s_time_lock);
#endif // WITH_FRC
return microseconds;
}
#endif // defined( WITH_FRC ) || defined( WITH_RTC )
void esp_time_impl_set_boot_time(uint64_t time_us)
{
spinlock_acquire(&s_time_lock, SPINLOCK_WAIT_FOREVER);
#ifdef WITH_RTC
REG_WRITE(RTC_BOOT_TIME_LOW_REG, (uint32_t) (time_us & 0xffffffff));
REG_WRITE(RTC_BOOT_TIME_HIGH_REG, (uint32_t) (time_us >> 32));
#else
s_boot_time = time_us;
#endif
spinlock_release(&s_time_lock);
}
uint64_t esp_clk_rtc_time(void)
{
#ifdef WITH_RTC
return esp_rtc_get_time_us();
#else
return 0;
#endif
}
uint64_t esp_time_impl_get_boot_time(void)
{
uint64_t result;
spinlock_acquire(&s_time_lock, SPINLOCK_WAIT_FOREVER);
#ifdef WITH_RTC
result = ((uint64_t) REG_READ(RTC_BOOT_TIME_LOW_REG)) + (((uint64_t) REG_READ(RTC_BOOT_TIME_HIGH_REG)) << 32);
#else
result = s_boot_time;
#endif
spinlock_release(&s_time_lock);
return result;
}
uint32_t esp_clk_slowclk_cal_get(void)
{
return REG_READ(RTC_SLOW_CLK_CAL_REG);
}
uint64_t esp_rtc_get_time_us(void)
{
const uint64_t ticks = rtc_time_get();
const uint32_t cal = esp_clk_slowclk_cal_get();
/* RTC counter result is up to 2^48, calibration factor is up to 2^24,
* for a 32kHz clock. We need to calculate (assuming no overflow):
* (ticks * cal) >> RTC_CLK_CAL_FRACT
*
* An overflow in the (ticks * cal) multiplication would cause time to
* wrap around after approximately 13 days, which is probably not enough
* for some applications.
* Therefore multiplication is split into two terms, for the lower 32-bit
* and the upper 16-bit parts of "ticks", i.e.:
* ((ticks_low + 2^32 * ticks_high) * cal) >> RTC_CLK_CAL_FRACT
*/
const uint64_t ticks_low = ticks & UINT32_MAX;
const uint64_t ticks_high = ticks >> 32;
return ((ticks_low * cal) >> RTC_CLK_CAL_FRACT) +
((ticks_high * cal) << (32 - RTC_CLK_CAL_FRACT));
}
void esp_clk_slowclk_cal_set(uint32_t new_cal)
{
#if defined(WITH_RTC)
/* To force monotonic time values even when clock calibration value changes,
* we adjust boot time, given current time and the new calibration value:
* T = boot_time_old + cur_cal * ticks / 2^19
* T = boot_time_adj + new_cal * ticks / 2^19
* which results in:
* boot_time_adj = boot_time_old + ticks * (cur_cal - new_cal) / 2^19
*/
const int64_t ticks = (int64_t) rtc_time_get();
const uint32_t cur_cal = REG_READ(RTC_SLOW_CLK_CAL_REG);
int32_t cal_diff = (int32_t) (cur_cal - new_cal);
int64_t boot_time_diff = ticks * cal_diff / (1LL << RTC_CLK_CAL_FRACT);
uint64_t boot_time_adj = esp_time_impl_get_boot_time() + boot_time_diff;
esp_time_impl_set_boot_time(boot_time_adj);
#endif // WITH_RTC
REG_WRITE(RTC_SLOW_CLK_CAL_REG, new_cal);
}
void esp_set_time_from_rtc(void)
{
#if defined( WITH_FRC ) && defined( WITH_RTC )
// initialize time from RTC clock
s_microseconds_offset = esp_rtc_get_time_us() - esp_system_get_time();
#endif // WITH_FRC && WITH_RTC
}
void esp_sync_counters_rtc_and_frc(void)
{
#if defined( WITH_FRC ) && defined( WITH_RTC )
struct timeval tv;
gettimeofday(&tv, NULL);
settimeofday(&tv, NULL);
int64_t s_microseconds_offset_cur = esp_rtc_get_time_us() - esp_system_get_time();
esp_time_impl_set_boot_time(esp_time_impl_get_boot_time() + ((int64_t)s_microseconds_offset - s_microseconds_offset_cur));
#endif
}
void esp_time_impl_init(void)
{
esp_set_time_from_rtc();
}

View File

@ -0,0 +1,26 @@
// Copyright 2020 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
void esp_time_impl_init(void);
uint64_t esp_time_impl_get_time(void);
uint64_t esp_time_impl_get_time_since_boot(void);
uint32_t esp_time_impl_get_time_resolution(void);
void esp_time_impl_set_boot_time(uint64_t t);
uint64_t esp_time_impl_get_boot_time(void);

View File

@ -13,6 +13,13 @@
#include "test_utils.h"
#include "esp_log.h"
#include "esp_rom_sys.h"
#include "esp_system.h"
#if CONFIG_IDF_TARGET_ESP32
#include "esp32/clk.h"
#elif CONFIG_IDF_TARGET_ESP32S2
#include "esp32s2/clk.h"
#endif
#if portNUM_PROCESSORS == 2
@ -379,8 +386,8 @@ void test_posix_timers_clock (void)
ts.tv_nsec = 100000000L;
TEST_ASSERT(clock_settime(CLOCK_REALTIME, &ts) == 0);
TEST_ASSERT(gettimeofday(&now, NULL) == 0);
TEST_ASSERT(now.tv_sec == ts.tv_sec);
TEST_ASSERT_INT_WITHIN(5000L, now.tv_usec, ts.tv_nsec / 1000L);
TEST_ASSERT_EQUAL(ts.tv_sec, now.tv_sec);
TEST_ASSERT_INT_WITHIN(5000L, ts.tv_nsec / 1000L, now.tv_usec);
TEST_ASSERT(clock_settime(CLOCK_MONOTONIC, &ts) == -1);

View File

@ -21,26 +21,21 @@
#include <sys/reent.h>
#include <sys/time.h>
#include <sys/times.h>
#include <sys/lock.h>
#include "esp_system.h"
#include "esp_attr.h"
#include "esp_intr_alloc.h"
#include "esp_timer.h"
#include "soc/soc.h"
#include "soc/rtc.h"
#include "soc/frc_timer_reg.h"
#include "freertos/FreeRTOS.h"
#include "freertos/xtensa_api.h"
#include "freertos/task.h"
#include "limits.h"
#include "esp_private/system_internal.h"
#include "soc/spinlock.h"
#include "soc/rtc.h"
#include "esp_time_impl.h"
#include "sdkconfig.h"
#include "esp_rom_sys.h"
#if CONFIG_IDF_TARGET_ESP32
#include "esp32/clk.h"
#include "esp32/rom/rtc.h"
#elif CONFIG_IDF_TARGET_ESP32S2
#include "esp32s2/clk.h"
#include "esp32s2/rom/rtc.h"
#endif
#ifdef CONFIG_SDK_TOOLCHAIN_SUPPORTS_TIME_WIDE_64_BITS
_Static_assert(sizeof(time_t) == 8, "The toolchain does not support time_t wide 64-bits");
@ -48,161 +43,95 @@ _Static_assert(sizeof(time_t) == 8, "The toolchain does not support time_t wide
_Static_assert(sizeof(time_t) == 4, "The toolchain supports time_t wide 64-bits. Please enable CONFIG_SDK_TOOLCHAIN_SUPPORTS_TIME_WIDE_64_BITS.");
#endif
#if defined( CONFIG_ESP32_TIME_SYSCALL_USE_RTC ) || defined( CONFIG_ESP32_TIME_SYSCALL_USE_RTC_FRC1 ) || defined( CONFIG_ESP32S2_TIME_SYSCALL_USE_RTC ) || defined( CONFIG_ESP32S2_TIME_SYSCALL_USE_RTC_FRC1 )
#define WITH_RTC 1
#if !CONFIG_ESP32_TIME_SYSCALL_USE_NONE && !CONFIG_ESP32S2_TIME_SYSCALL_USE_NONE
#define IMPL_NEWLIB_TIME_FUNCS 1
#endif
#if defined( CONFIG_ESP32_TIME_SYSCALL_USE_FRC1 ) || defined( CONFIG_ESP32_TIME_SYSCALL_USE_RTC_FRC1 ) || defined( CONFIG_ESP32S2_TIME_SYSCALL_USE_FRC1 ) || defined( CONFIG_ESP32S2_TIME_SYSCALL_USE_RTC_FRC1 )
#define WITH_FRC 1
#endif
#ifdef WITH_RTC
static uint64_t get_rtc_time_us(void)
{
const uint64_t ticks = rtc_time_get();
const uint32_t cal = esp_clk_slowclk_cal_get();
/* RTC counter result is up to 2^48, calibration factor is up to 2^24,
* for a 32kHz clock. We need to calculate (assuming no overflow):
* (ticks * cal) >> RTC_CLK_CAL_FRACT
*
* An overflow in the (ticks * cal) multiplication would cause time to
* wrap around after approximately 13 days, which is probably not enough
* for some applications.
* Therefore multiplication is split into two terms, for the lower 32-bit
* and the upper 16-bit parts of "ticks", i.e.:
* ((ticks_low + 2^32 * ticks_high) * cal) >> RTC_CLK_CAL_FRACT
*/
const uint64_t ticks_low = ticks & UINT32_MAX;
const uint64_t ticks_high = ticks >> 32;
return ((ticks_low * cal) >> RTC_CLK_CAL_FRACT) +
((ticks_high * cal) << (32 - RTC_CLK_CAL_FRACT));
}
#endif // WITH_RTC
// s_boot_time: time from Epoch to the first boot time
#ifdef WITH_RTC
// when RTC is used to persist time, two RTC_STORE registers are used to store boot time
#elif defined(WITH_FRC)
static uint64_t s_boot_time;
#endif // WITH_RTC
#if defined(WITH_RTC) || defined(WITH_FRC)
static _lock_t s_boot_time_lock;
static _lock_t s_adjust_time_lock;
#if IMPL_NEWLIB_TIME_FUNCS
// stores the start time of the slew
static uint64_t adjtime_start = 0;
static uint64_t s_adjtime_start_us;
// is how many microseconds total to slew
static int64_t adjtime_total_correction = 0;
#define ADJTIME_CORRECTION_FACTOR 6
static uint64_t get_time_since_boot(void);
#endif
// Offset between FRC timer and the RTC.
// Initialized after reset or light sleep.
#if defined(WITH_RTC) && defined(WITH_FRC)
uint64_t s_microseconds_offset;
#endif
static int64_t s_adjtime_total_correction_us;
#if defined(WITH_RTC) || defined(WITH_FRC)
static void set_boot_time(uint64_t time_us)
{
_lock_acquire(&s_boot_time_lock);
#ifdef WITH_RTC
REG_WRITE(RTC_BOOT_TIME_LOW_REG, (uint32_t) (time_us & 0xffffffff));
REG_WRITE(RTC_BOOT_TIME_HIGH_REG, (uint32_t) (time_us >> 32));
#else
s_boot_time = time_us;
#endif
_lock_release(&s_boot_time_lock);
}
static uint64_t get_boot_time(void)
{
uint64_t result;
_lock_acquire(&s_boot_time_lock);
#ifdef WITH_RTC
result = ((uint64_t) REG_READ(RTC_BOOT_TIME_LOW_REG)) + (((uint64_t) REG_READ(RTC_BOOT_TIME_HIGH_REG)) << 32);
#else
result = s_boot_time;
#endif
_lock_release(&s_boot_time_lock);
return result;
}
static spinlock_t s_time_lock = SPINLOCK_INITIALIZER;
// This function gradually changes boot_time to the correction value and immediately updates it.
static uint64_t adjust_boot_time(void)
{
uint64_t boot_time = get_boot_time();
if ((boot_time == 0) || (get_time_since_boot() < adjtime_start)) {
adjtime_start = 0;
#define ADJTIME_CORRECTION_FACTOR 6
uint64_t boot_time = esp_time_impl_get_boot_time();
if ((boot_time == 0) || (esp_time_impl_get_time_since_boot() < s_adjtime_start_us)) {
s_adjtime_start_us = 0;
}
if (adjtime_start > 0) {
uint64_t since_boot = get_time_since_boot();
// If to call this function once per second, then (since_boot - adjtime_start) will be 1_000_000 (1 second),
if (s_adjtime_start_us > 0) {
uint64_t since_boot = esp_time_impl_get_time_since_boot();
// If to call this function once per second, then (since_boot - s_adjtime_start_us) will be 1_000_000 (1 second),
// and the correction will be equal to (1_000_000us >> 6) = 15_625 us.
// The minimum possible correction step can be (64us >> 6) = 1us.
// Example: if the time error is 1 second, then it will be compensate for 1 sec / 0,015625 = 64 seconds.
int64_t correction = (since_boot >> ADJTIME_CORRECTION_FACTOR) - (adjtime_start >> ADJTIME_CORRECTION_FACTOR);
int64_t correction = (since_boot >> ADJTIME_CORRECTION_FACTOR) - (s_adjtime_start_us >> ADJTIME_CORRECTION_FACTOR);
if (correction > 0) {
adjtime_start = since_boot;
if (adjtime_total_correction < 0) {
if ((adjtime_total_correction + correction) >= 0) {
boot_time = boot_time + adjtime_total_correction;
adjtime_start = 0;
s_adjtime_start_us = since_boot;
if (s_adjtime_total_correction_us < 0) {
if ((s_adjtime_total_correction_us + correction) >= 0) {
boot_time = boot_time + s_adjtime_total_correction_us;
s_adjtime_start_us = 0;
} else {
adjtime_total_correction += correction;
s_adjtime_total_correction_us += correction;
boot_time -= correction;
}
} else {
if ((adjtime_total_correction - correction) <= 0) {
boot_time = boot_time + adjtime_total_correction;
adjtime_start = 0;
if ((s_adjtime_total_correction_us - correction) <= 0) {
boot_time = boot_time + s_adjtime_total_correction_us;
s_adjtime_start_us = 0;
} else {
adjtime_total_correction -= correction;
s_adjtime_total_correction_us -= correction;
boot_time += correction;
}
}
set_boot_time(boot_time);
esp_time_impl_set_boot_time(boot_time);
}
}
return boot_time;
}
// Get the adjusted boot time.
static uint64_t get_adjusted_boot_time (void)
static uint64_t get_adjusted_boot_time(void)
{
_lock_acquire(&s_adjust_time_lock);
spinlock_acquire(&s_time_lock, SPINLOCK_WAIT_FOREVER);
uint64_t adjust_time = adjust_boot_time();
_lock_release(&s_adjust_time_lock);
spinlock_release(&s_time_lock);
return adjust_time;
}
// Applying the accumulated correction to boot_time and stopping the smooth time adjustment.
// Applying the accumulated correction to base_time and stopping the smooth time adjustment.
static void adjtime_corr_stop (void)
{
_lock_acquire(&s_adjust_time_lock);
if (adjtime_start != 0){
spinlock_acquire(&s_time_lock, SPINLOCK_WAIT_FOREVER);
if (s_adjtime_start_us != 0){
adjust_boot_time();
adjtime_start = 0;
s_adjtime_start_us = 0;
}
_lock_release(&s_adjust_time_lock);
spinlock_release(&s_time_lock);
}
#endif //defined(WITH_RTC) || defined(WITH_FRC)
#endif
int adjtime(const struct timeval *delta, struct timeval *outdelta)
{
#if defined( WITH_FRC ) || defined( WITH_RTC )
#if IMPL_NEWLIB_TIME_FUNCS
if(outdelta != NULL){
_lock_acquire(&s_adjust_time_lock);
spinlock_acquire(&s_time_lock, SPINLOCK_WAIT_FOREVER);
adjust_boot_time();
if (adjtime_start != 0) {
outdelta->tv_sec = adjtime_total_correction / 1000000L;
outdelta->tv_usec = adjtime_total_correction % 1000000L;
if (s_adjtime_start_us != 0) {
outdelta->tv_sec = s_adjtime_total_correction_us / 1000000L;
outdelta->tv_usec = s_adjtime_total_correction_us % 1000000L;
} else {
outdelta->tv_sec = 0;
outdelta->tv_usec = 0;
}
_lock_release(&s_adjust_time_lock);
spinlock_release(&s_time_lock);
}
if(delta != NULL){
int64_t sec = delta->tv_sec;
@ -215,59 +144,16 @@ int adjtime(const struct timeval *delta, struct timeval *outdelta)
* and the delta of the second call is not NULL, the earlier tuning is stopped,
* but the already completed part of the adjustment is not canceled.
*/
_lock_acquire(&s_adjust_time_lock);
// If correction is already in progress (adjtime_start != 0), then apply accumulated corrections.
spinlock_acquire(&s_time_lock, SPINLOCK_WAIT_FOREVER);
// If correction is already in progress (s_adjtime_start_time_us != 0), then apply accumulated corrections.
adjust_boot_time();
adjtime_start = get_time_since_boot();
adjtime_total_correction = sec * 1000000L + usec;
_lock_release(&s_adjust_time_lock);
s_adjtime_start_us = esp_time_impl_get_time_since_boot();
s_adjtime_total_correction_us = sec * 1000000L + usec;
spinlock_release(&s_time_lock);
}
return 0;
#else
return -1;
#endif
}
void esp_clk_slowclk_cal_set(uint32_t new_cal)
{
#if defined(WITH_RTC)
/* To force monotonic time values even when clock calibration value changes,
* we adjust boot time, given current time and the new calibration value:
* T = boot_time_old + cur_cal * ticks / 2^19
* T = boot_time_adj + new_cal * ticks / 2^19
* which results in:
* boot_time_adj = boot_time_old + ticks * (cur_cal - new_cal) / 2^19
*/
const int64_t ticks = (int64_t) rtc_time_get();
const uint32_t cur_cal = REG_READ(RTC_SLOW_CLK_CAL_REG);
int32_t cal_diff = (int32_t) (cur_cal - new_cal);
int64_t boot_time_diff = ticks * cal_diff / (1LL << RTC_CLK_CAL_FRACT);
uint64_t boot_time_adj = get_boot_time() + boot_time_diff;
set_boot_time(boot_time_adj);
#endif // WITH_RTC
REG_WRITE(RTC_SLOW_CLK_CAL_REG, new_cal);
}
uint32_t esp_clk_slowclk_cal_get(void)
{
return REG_READ(RTC_SLOW_CLK_CAL_REG);
}
void esp_set_time_from_rtc(void)
{
#if defined( WITH_FRC ) && defined( WITH_RTC )
// initialize time from RTC clock
s_microseconds_offset = get_rtc_time_us() - esp_timer_get_time();
#endif // WITH_FRC && WITH_RTC
}
uint64_t esp_clk_rtc_time(void)
{
#ifdef WITH_RTC
return get_rtc_time_us();
#else
return 0;
#else
return -1;
#endif
}
@ -283,29 +169,13 @@ clock_t IRAM_ATTR _times_r(struct _reent *r, struct tms *ptms)
return (clock_t) tv.tv_sec;
}
#if defined( WITH_FRC ) || defined( WITH_RTC )
static uint64_t get_time_since_boot(void)
{
uint64_t microseconds = 0;
#ifdef WITH_FRC
#ifdef WITH_RTC
microseconds = s_microseconds_offset + esp_timer_get_time();
#else
microseconds = esp_timer_get_time();
#endif // WITH_RTC
#elif defined(WITH_RTC)
microseconds = get_rtc_time_us();
#endif // WITH_FRC
return microseconds;
}
#endif // defined( WITH_FRC ) || defined( WITH_RTC )
int IRAM_ATTR _gettimeofday_r(struct _reent *r, struct timeval *tv, void *tz)
{
(void) tz;
#if defined( WITH_FRC ) || defined( WITH_RTC )
#if IMPL_NEWLIB_TIME_FUNCS
if (tv) {
uint64_t microseconds = get_adjusted_boot_time() + get_time_since_boot();
uint64_t microseconds = get_adjusted_boot_time() + esp_time_impl_get_time_since_boot();
tv->tv_sec = microseconds / 1000000;
tv->tv_usec = microseconds % 1000000;
}
@ -313,18 +183,18 @@ int IRAM_ATTR _gettimeofday_r(struct _reent *r, struct timeval *tv, void *tz)
#else
__errno_r(r) = ENOSYS;
return -1;
#endif // defined( WITH_FRC ) || defined( WITH_RTC )
#endif
}
int settimeofday(const struct timeval *tv, const struct timezone *tz)
{
(void) tz;
#if defined( WITH_FRC ) || defined( WITH_RTC )
#if IMPL_NEWLIB_TIME_FUNCS
if (tv) {
adjtime_corr_stop();
uint64_t now = ((uint64_t) tv->tv_sec) * 1000000LL + tv->tv_usec;
uint64_t since_boot = get_time_since_boot();
set_boot_time(now - since_boot);
uint64_t since_boot = esp_time_impl_get_time_since_boot();
esp_time_impl_set_boot_time(now - since_boot);
}
return 0;
#else
@ -353,48 +223,9 @@ unsigned int sleep(unsigned int seconds)
return 0;
}
uint32_t system_get_time(void)
int clock_settime(clockid_t clock_id, const struct timespec *tp)
{
#if defined( WITH_FRC ) || defined( WITH_RTC )
return get_time_since_boot();
#else
return 0;
#endif
}
uint32_t system_get_current_time(void) __attribute__((alias("system_get_time")));
uint32_t system_relative_time(uint32_t current_time)
{
#if defined( WITH_FRC ) || defined( WITH_RTC )
return get_time_since_boot() - current_time;
#else
return 0;
#endif
}
uint64_t system_get_rtc_time(void)
{
#ifdef WITH_RTC
return get_rtc_time_us();
#else
return 0;
#endif
}
void esp_sync_counters_rtc_and_frc(void)
{
#if defined( WITH_FRC ) && defined( WITH_RTC )
adjtime_corr_stop();
int64_t s_microseconds_offset_cur = get_rtc_time_us() - esp_timer_get_time();
set_boot_time(get_adjusted_boot_time() + ((int64_t)s_microseconds_offset - s_microseconds_offset_cur));
#endif
}
int clock_settime (clockid_t clock_id, const struct timespec *tp)
{
#if defined( WITH_FRC ) || defined( WITH_RTC )
#if IMPL_NEWLIB_TIME_FUNCS
if (tp == NULL) {
errno = EINVAL;
return -1;
@ -419,7 +250,7 @@ int clock_settime (clockid_t clock_id, const struct timespec *tp)
int clock_gettime (clockid_t clock_id, struct timespec *tp)
{
#if defined( WITH_FRC ) || defined( WITH_RTC )
#if IMPL_NEWLIB_TIME_FUNCS
if (tp == NULL) {
errno = EINVAL;
return -1;
@ -433,11 +264,7 @@ int clock_gettime (clockid_t clock_id, struct timespec *tp)
tp->tv_nsec = tv.tv_usec * 1000L;
break;
case CLOCK_MONOTONIC:
#if defined( WITH_FRC )
monotonic_time_us = (uint64_t) esp_timer_get_time();
#elif defined( WITH_RTC )
monotonic_time_us = get_rtc_time_us();
#endif // WITH_FRC
monotonic_time_us = esp_time_impl_get_time();
tp->tv_sec = monotonic_time_us / 1000000LL;
tp->tv_nsec = (monotonic_time_us % 1000000LL) * 1000L;
break;
@ -454,23 +281,23 @@ int clock_gettime (clockid_t clock_id, struct timespec *tp)
int clock_getres (clockid_t clock_id, struct timespec *res)
{
#if defined( WITH_FRC ) || defined( WITH_RTC )
#if IMPL_NEWLIB_TIME_FUNCS
if (res == NULL) {
errno = EINVAL;
return -1;
}
#if defined( WITH_FRC )
res->tv_sec = 0;
res->tv_nsec = 1000L;
#elif defined( WITH_RTC )
res->tv_sec = 0;
uint32_t rtc_freq = rtc_clk_slow_freq_get_hz();
assert(rtc_freq != 0);
res->tv_nsec = 1000000000L / rtc_freq;
#endif // WITH_FRC
res->tv_nsec = esp_system_get_time_resolution() * 1000;
return 0;
#else
errno = ENOSYS;
return -1;
#endif
}
void esp_newlib_time_init(void)
{
esp_time_impl_init();
}

View File

@ -645,6 +645,8 @@ rtc_vddsdio_config_t rtc_vddsdio_get_config(void);
*/
void rtc_vddsdio_set_config(rtc_vddsdio_config_t config);
#ifdef __cplusplus
}
#endif

View File

@ -809,6 +809,7 @@ rtc_vddsdio_config_t rtc_vddsdio_get_config(void);
*/
void rtc_vddsdio_set_config(rtc_vddsdio_config_t config);
#ifdef __cplusplus
}
#endif

View File

@ -183,5 +183,4 @@ void rtc_clk_wait_for_slow_cycle(void) //This function may not by useful any mor
while (GET_PERI_REG_MASK(RTC_CNTL_SLOW_CLK_CONF_REG, RTC_CNTL_SLOW_CLK_NEXT_EDGE)) {
esp_rom_delay_us(1);
}
}
}