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