1 /*
2  * SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <errno.h>
8 #include <stdlib.h>
9 #include <time.h>
10 #include <reent.h>
11 #include <unistd.h>
12 #include <sys/types.h>
13 #include <sys/reent.h>
14 #include <sys/time.h>
15 #include <sys/times.h>
16 #include <sys/lock.h>
17 
18 #include "esp_system.h"
19 #include "esp_attr.h"
20 #include "esp_rom_sys.h"
21 #include "freertos/FreeRTOS.h"
22 #include "freertos/task.h"
23 
24 #include "esp_private/system_internal.h"
25 
26 #include "soc/rtc.h"
27 
28 #include "esp_time_impl.h"
29 
30 #include "sdkconfig.h"
31 
32 #if !CONFIG_ESP_TIME_FUNCS_USE_NONE
33 #define IMPL_NEWLIB_TIME_FUNCS 1
34 #endif
35 
36 #if IMPL_NEWLIB_TIME_FUNCS
37 // stores the start time of the slew
38 static uint64_t s_adjtime_start_us;
39 // is how many microseconds total to slew
40 static int64_t  s_adjtime_total_correction_us;
41 
42 static _lock_t s_time_lock;
43 
44 // This function gradually changes boot_time to the correction value and immediately updates it.
adjust_boot_time(void)45 static uint64_t adjust_boot_time(void)
46 {
47     #define ADJTIME_CORRECTION_FACTOR 6
48 
49     uint64_t boot_time = esp_time_impl_get_boot_time();
50     if ((boot_time == 0) || (esp_time_impl_get_time_since_boot() < s_adjtime_start_us)) {
51         s_adjtime_start_us = 0;
52     }
53     if (s_adjtime_start_us > 0) {
54         uint64_t since_boot = esp_time_impl_get_time_since_boot();
55         // If to call this function once per second, then (since_boot - s_adjtime_start_us) will be 1_000_000 (1 second),
56         // and the correction will be equal to (1_000_000us >> 6) = 15_625 us.
57         // The minimum possible correction step can be (64us >> 6) = 1us.
58         // Example: if the time error is 1 second, then it will be compensate for 1 sec / 0,015625 = 64 seconds.
59         int64_t correction = (since_boot >> ADJTIME_CORRECTION_FACTOR) - (s_adjtime_start_us >> ADJTIME_CORRECTION_FACTOR);
60         if (correction > 0) {
61             s_adjtime_start_us = since_boot;
62             if (s_adjtime_total_correction_us < 0) {
63                 if ((s_adjtime_total_correction_us + correction) >= 0) {
64                     boot_time = boot_time + s_adjtime_total_correction_us;
65                     s_adjtime_start_us = 0;
66                 } else {
67                     s_adjtime_total_correction_us += correction;
68                     boot_time -= correction;
69                 }
70             } else {
71                 if ((s_adjtime_total_correction_us - correction) <= 0) {
72                     boot_time = boot_time + s_adjtime_total_correction_us;
73                     s_adjtime_start_us = 0;
74                 } else {
75                     s_adjtime_total_correction_us -= correction;
76                     boot_time += correction;
77                 }
78             }
79             esp_time_impl_set_boot_time(boot_time);
80         }
81     }
82     return boot_time;
83 }
84 
85 
86 // Get the adjusted boot time.
get_adjusted_boot_time(void)87 static uint64_t get_adjusted_boot_time(void)
88 {
89     _lock_acquire(&s_time_lock);
90     uint64_t adjust_time = adjust_boot_time();
91     _lock_release(&s_time_lock);
92     return adjust_time;
93 }
94 
95 // Applying the accumulated correction to base_time and stopping the smooth time adjustment.
adjtime_corr_stop(void)96 static void adjtime_corr_stop (void)
97 {
98     _lock_acquire(&s_time_lock);
99     if (s_adjtime_start_us != 0){
100         adjust_boot_time();
101         s_adjtime_start_us = 0;
102     }
103     _lock_release(&s_time_lock);
104 }
105 #endif
106 
adjtime(const struct timeval * delta,struct timeval * outdelta)107 int adjtime(const struct timeval *delta, struct timeval *outdelta)
108 {
109 #if IMPL_NEWLIB_TIME_FUNCS
110     if(outdelta != NULL){
111         _lock_acquire(&s_time_lock);
112         adjust_boot_time();
113         if (s_adjtime_start_us != 0) {
114             outdelta->tv_sec    = s_adjtime_total_correction_us / 1000000L;
115             outdelta->tv_usec   = s_adjtime_total_correction_us % 1000000L;
116         } else {
117             outdelta->tv_sec    = 0;
118             outdelta->tv_usec   = 0;
119         }
120         _lock_release(&s_time_lock);
121     }
122     if(delta != NULL){
123         int64_t sec  = delta->tv_sec;
124         int64_t usec = delta->tv_usec;
125         if(llabs(sec) > ((INT_MAX / 1000000L) - 1L)) {
126             errno = EINVAL;
127             return -1;
128         }
129         /*
130         * If adjusting the system clock by adjtime () is already done during the second call adjtime (),
131         * and the delta of the second call is not NULL, the earlier tuning is stopped,
132         * but the already completed part of the adjustment is not canceled.
133         */
134         _lock_acquire(&s_time_lock);
135         // If correction is already in progress (s_adjtime_start_time_us != 0), then apply accumulated corrections.
136         adjust_boot_time();
137         s_adjtime_start_us = esp_time_impl_get_time_since_boot();
138         s_adjtime_total_correction_us = sec * 1000000L + usec;
139         _lock_release(&s_time_lock);
140     }
141     return 0;
142 #else
143     errno = ENOSYS;
144     return -1;
145 #endif
146 }
147 
_times_r(struct _reent * r,struct tms * ptms)148 clock_t IRAM_ATTR _times_r(struct _reent *r, struct tms *ptms)
149 {
150     clock_t t = xTaskGetTickCount() * (portTICK_PERIOD_MS * CLK_TCK / 1000);
151     ptms->tms_cstime = 0;
152     ptms->tms_cutime = 0;
153     ptms->tms_stime = t;
154     ptms->tms_utime = 0;
155     struct timeval tv = {0, 0};
156     _gettimeofday_r(r, &tv, NULL);
157     return (clock_t) tv.tv_sec;
158 }
159 
_gettimeofday_r(struct _reent * r,struct timeval * tv,void * tz)160 int IRAM_ATTR _gettimeofday_r(struct _reent *r, struct timeval *tv, void *tz)
161 {
162     (void) tz;
163 
164 #if IMPL_NEWLIB_TIME_FUNCS
165     if (tv) {
166         uint64_t microseconds = get_adjusted_boot_time() + esp_time_impl_get_time_since_boot();
167         tv->tv_sec = microseconds / 1000000;
168         tv->tv_usec = microseconds % 1000000;
169     }
170     return 0;
171 #else
172     __errno_r(r) = ENOSYS;
173     return -1;
174 #endif
175 }
176 
settimeofday(const struct timeval * tv,const struct timezone * tz)177 int settimeofday(const struct timeval *tv, const struct timezone *tz)
178 {
179     (void) tz;
180 #if IMPL_NEWLIB_TIME_FUNCS
181     if (tv) {
182         adjtime_corr_stop();
183         uint64_t now = ((uint64_t) tv->tv_sec) * 1000000LL + tv->tv_usec;
184         uint64_t since_boot = esp_time_impl_get_time_since_boot();
185         esp_time_impl_set_boot_time(now - since_boot);
186     }
187     return 0;
188 #else
189     errno = ENOSYS;
190     return -1;
191 #endif
192 }
193 
usleep(useconds_t us)194 int usleep(useconds_t us)
195 {
196     const int us_per_tick = portTICK_PERIOD_MS * 1000;
197     if (us < us_per_tick) {
198         esp_rom_delay_us((uint32_t) us);
199     } else {
200         /* since vTaskDelay(1) blocks for anywhere between 0 and portTICK_PERIOD_MS,
201          * round up to compensate.
202          */
203         vTaskDelay((us + us_per_tick - 1) / us_per_tick);
204     }
205     return 0;
206 }
207 
sleep(unsigned int seconds)208 unsigned int sleep(unsigned int seconds)
209 {
210     usleep(seconds*1000000UL);
211     return 0;
212 }
213 
clock_settime(clockid_t clock_id,const struct timespec * tp)214 int clock_settime(clockid_t clock_id, const struct timespec *tp)
215 {
216 #if IMPL_NEWLIB_TIME_FUNCS
217     if (tp == NULL) {
218         errno = EINVAL;
219         return -1;
220     }
221     struct timeval tv;
222     switch (clock_id) {
223         case CLOCK_REALTIME:
224             tv.tv_sec = tp->tv_sec;
225             tv.tv_usec = tp->tv_nsec / 1000L;
226             settimeofday(&tv, NULL);
227             break;
228         default:
229             errno = EINVAL;
230             return -1;
231     }
232     return 0;
233 #else
234     errno = ENOSYS;
235     return -1;
236 #endif
237 }
238 
clock_gettime(clockid_t clock_id,struct timespec * tp)239 int clock_gettime (clockid_t clock_id, struct timespec *tp)
240 {
241 #if IMPL_NEWLIB_TIME_FUNCS
242     if (tp == NULL) {
243         errno = EINVAL;
244         return -1;
245     }
246     struct timeval tv;
247     uint64_t monotonic_time_us = 0;
248     switch (clock_id) {
249         case CLOCK_REALTIME:
250             _gettimeofday_r(NULL, &tv, NULL);
251             tp->tv_sec = tv.tv_sec;
252             tp->tv_nsec = tv.tv_usec * 1000L;
253             break;
254         case CLOCK_MONOTONIC:
255             monotonic_time_us = esp_time_impl_get_time();
256             tp->tv_sec = monotonic_time_us / 1000000LL;
257             tp->tv_nsec = (monotonic_time_us % 1000000LL) * 1000L;
258             break;
259         default:
260             errno = EINVAL;
261             return -1;
262     }
263     return 0;
264 #else
265     errno = ENOSYS;
266     return -1;
267 #endif
268 }
269 
clock_getres(clockid_t clock_id,struct timespec * res)270 int clock_getres (clockid_t clock_id, struct timespec *res)
271 {
272 #if IMPL_NEWLIB_TIME_FUNCS
273     if (res == NULL) {
274         errno = EINVAL;
275         return -1;
276     }
277 
278     res->tv_sec = 0;
279     res->tv_nsec = esp_system_get_time_resolution();
280 
281     return 0;
282 #else
283     errno = ENOSYS;
284     return -1;
285 #endif
286 }
287 
esp_newlib_time_init(void)288 void esp_newlib_time_init(void)
289 {
290     esp_time_impl_init();
291 }
292