source: mainline/uspace/lib/c/generic/time.c@ 8867cf6

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 8867cf6 was bd41ac52, checked in by Jakub Jermar <jakub@…>, 7 years ago

Get rid of sys/time.h

This commit moves the POSIX-like time functionality from libc's
sys/time.h to libposix and introduces C11-like or HelenOS-specific
interfaces to libc.

Specifically, use of sys/time.h, struct timeval, suseconds_t and
gettimeofday is replaced by time.h (C11), struct timespec (C11), usec_t
(HelenOS) and getuptime / getrealtime (HelenOS).

Also attempt to fix the implementation of clock() to return microseconds
(clocks) rather than processor cycles and move it to libc.

  • Property mode set to 100644
File size: 25.0 KB
RevLine 
[0b99e40]1/*
[df4ed85]2 * Copyright (c) 2006 Ondrej Palkovsky
[c2b0e10]3 * Copyright (c) 2011 Petr Koupy
4 * Copyright (c) 2011 Jiri Zarevucky
[0b99e40]5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 *
11 * - Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * - Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * - The name of the author may not be used to endorse or promote products
17 * derived from this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[b2951e2]29 */
30
[a46da63]31/** @addtogroup libc
[b2951e2]32 * @{
33 */
34/** @file
[22e6802]35 */
[0b99e40]36
[6119f24]37#include <time.h>
[3e6a98c5]38#include <stdbool.h>
[05882233]39#include <barrier.h>
[2c577e0b]40#include <macros.h>
[6119f24]41#include <errno.h>
42#include <sysinfo.h>
43#include <as.h>
44#include <ddi.h>
[d9ece1cb]45#include <libc.h>
[c2b0e10]46#include <stdint.h>
47#include <stdio.h>
48#include <ctype.h>
[f7e69f5]49#include <assert.h>
[3a58347]50#include <loc.h>
51#include <device/clock_dev.h>
[bd41ac52]52#include <stats.h>
[c61d34b]53
[1ab8539]54#define ASCTIME_BUF_LEN 26
55
56#define HOURS_PER_DAY 24
57#define MINS_PER_HOUR 60
58#define SECS_PER_MIN 60
[bd41ac52]59#define NSECS_PER_SEC 1000000000ll
[1ab8539]60#define MINS_PER_DAY (MINS_PER_HOUR * HOURS_PER_DAY)
61#define SECS_PER_HOUR (SECS_PER_MIN * MINS_PER_HOUR)
62#define SECS_PER_DAY (SECS_PER_HOUR * HOURS_PER_DAY)
[8219eb9]63
[2c577e0b]64/** Pointer to kernel shared variables with time */
[0b99e40]65struct {
[2d1fde3b]66 volatile sysarg_t seconds1;
[0b99e40]67 volatile sysarg_t useconds;
[2d1fde3b]68 volatile sysarg_t seconds2;
[0b99e40]69} *ktime = NULL;
70
[1ab8539]71static async_sess_t *clock_conn = NULL;
[c2b0e10]72
[bd41ac52]73/**
74 * Get CPU time used since the process invocation.
75 *
76 * @return Consumed microseconds by this process or -1 if not available.
77 */
78clock_t clock(void)
79{
80 static_assert(CLOCKS_PER_SEC == 1000000);
81
82 size_t count;
83 stats_cpu_t *cpu_stats = stats_get_cpus(&count);
84 if (!cpu_stats)
85 return (clock_t) -1;
86 if (!cpu_stats->frequency_mhz) {
87 free(cpu_stats);
88 return (clock_t) -1;
89 }
90
91 clock_t total_usecs = -1;
92 if (cpu_stats) {
93 stats_task_t *task_stats = stats_get_task(task_get_id());
94 if (task_stats) {
95 total_usecs = (clock_t) (task_stats->kcycles +
96 task_stats->ucycles) / cpu_stats->frequency_mhz;
97 free(task_stats);
98 }
99 free(cpu_stats);
100 }
101
102 return total_usecs;
103}
104
[1ab8539]105/** Check whether the year is a leap year.
[c2b0e10]106 *
107 * @param year Year since 1900 (e.g. for 1970, the value is 70).
[1ab8539]108 *
[c2b0e10]109 * @return true if year is a leap year, false otherwise
[1ab8539]110 *
[c2b0e10]111 */
[1ab8539]112static bool is_leap_year(time_t year)
[c2b0e10]113{
114 year += 1900;
[a35b458]115
[c2b0e10]116 if (year % 400 == 0)
117 return true;
[a35b458]118
[c2b0e10]119 if (year % 100 == 0)
120 return false;
[a35b458]121
[c2b0e10]122 if (year % 4 == 0)
123 return true;
[a35b458]124
[c2b0e10]125 return false;
126}
127
[1ab8539]128/** How many days there are in the given month
129 *
130 * Return how many days there are in the given month of the given year.
[c2b0e10]131 * Note that year is only taken into account if month is February.
132 *
133 * @param year Year since 1900 (can be negative).
[1ab8539]134 * @param mon Month of the year. 0 for January, 11 for December.
135 *
[c2b0e10]136 * @return Number of days in the specified month.
[1ab8539]137 *
[c2b0e10]138 */
[1ab8539]139static int days_in_month(time_t year, time_t mon)
[c2b0e10]140{
[1ab8539]141 assert(mon >= 0);
142 assert(mon <= 11);
[a35b458]143
[1ab8539]144 static int month_days[] = {
145 31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
146 };
[a35b458]147
[c2b0e10]148 if (mon == 1) {
[1ab8539]149 /* February */
[c2b0e10]150 year += 1900;
[1ab8539]151 return is_leap_year(year) ? 29 : 28;
[c2b0e10]152 }
[a35b458]153
[1ab8539]154 return month_days[mon];
[c2b0e10]155}
156
[1ab8539]157/** Which day of that year it is.
158 *
159 * For specified year, month and day of month, return which day of that year
[c2b0e10]160 * it is.
161 *
162 * For example, given date 2011-01-03, the corresponding expression is:
[1ab8539]163 * day_of_year(111, 0, 3) == 2
[c2b0e10]164 *
165 * @param year Year (year 1900 = 0, can be negative).
[1ab8539]166 * @param mon Month (January = 0).
[c2b0e10]167 * @param mday Day of month (First day is 1).
[1ab8539]168 *
[c2b0e10]169 * @return Day of year (First day is 0).
[1ab8539]170 *
[c2b0e10]171 */
[1ab8539]172static int day_of_year(time_t year, time_t mon, time_t mday)
[c2b0e10]173{
[1ab8539]174 static int mdays[] = {
175 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
176 };
[a35b458]177
[1ab8539]178 static int leap_mdays[] = {
179 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335
180 };
[a35b458]181
[1ab8539]182 return (is_leap_year(year) ? leap_mdays[mon] : mdays[mon]) + mday - 1;
[c2b0e10]183}
184
[1ab8539]185/** Integer division that rounds to negative infinity.
186 *
187 * Used by some functions in this module.
[c2b0e10]188 *
189 * @param op1 Dividend.
190 * @param op2 Divisor.
[1ab8539]191 *
[c2b0e10]192 * @return Rounded quotient.
[1ab8539]193 *
[c2b0e10]194 */
[1ab8539]195static time_t floor_div(time_t op1, time_t op2)
[c2b0e10]196{
[1ab8539]197 if ((op1 >= 0) || (op1 % op2 == 0))
[c2b0e10]198 return op1 / op2;
[a35b458]199
[1ab8539]200 return op1 / op2 - 1;
[c2b0e10]201}
202
[1ab8539]203/** Modulo that rounds to negative infinity.
204 *
205 * Used by some functions in this module.
[c2b0e10]206 *
207 * @param op1 Dividend.
208 * @param op2 Divisor.
[1ab8539]209 *
[c2b0e10]210 * @return Remainder.
[1ab8539]211 *
[c2b0e10]212 */
[1ab8539]213static time_t floor_mod(time_t op1, time_t op2)
[c2b0e10]214{
[1ab8539]215 time_t div = floor_div(op1, op2);
[a35b458]216
[1ab8539]217 /*
218 * (a / b) * b + a % b == a
219 * Thus: a % b == a - (a / b) * b
220 */
[a35b458]221
[1ab8539]222 time_t result = op1 - div * op2;
[a35b458]223
[1ab8539]224 /* Some paranoid checking to ensure there is mistake here. */
[c2b0e10]225 assert(result >= 0);
226 assert(result < op2);
227 assert(div * op2 + result == op1);
[a35b458]228
[c2b0e10]229 return result;
230}
231
[1ab8539]232/** Number of days since the Epoch.
233 *
[c2b0e10]234 * Epoch is 1970-01-01, which is also equal to day 0.
235 *
236 * @param year Year (year 1900 = 0, may be negative).
[1ab8539]237 * @param mon Month (January = 0).
[c2b0e10]238 * @param mday Day of month (first day = 1).
[1ab8539]239 *
[c2b0e10]240 * @return Number of days since the Epoch.
[1ab8539]241 *
[c2b0e10]242 */
[1ab8539]243static time_t days_since_epoch(time_t year, time_t mon, time_t mday)
[c2b0e10]244{
[1ab8539]245 return (year - 70) * 365 + floor_div(year - 69, 4) -
246 floor_div(year - 1, 100) + floor_div(year + 299, 400) +
247 day_of_year(year, mon, mday);
[c2b0e10]248}
249
[1ab8539]250/** Seconds since the Epoch.
251 *
252 * See also days_since_epoch().
253 *
[c2b0e10]254 * @param tm Normalized broken-down time.
[1ab8539]255 *
[c2b0e10]256 * @return Number of seconds since the epoch, not counting leap seconds.
[1ab8539]257 *
[c2b0e10]258 */
[1ab8539]259static time_t secs_since_epoch(const struct tm *tm)
[c2b0e10]260{
[1ab8539]261 return days_since_epoch(tm->tm_year, tm->tm_mon, tm->tm_mday) *
[c2b0e10]262 SECS_PER_DAY + tm->tm_hour * SECS_PER_HOUR +
263 tm->tm_min * SECS_PER_MIN + tm->tm_sec;
264}
265
[1ab8539]266/** Which day of week the specified date is.
267 *
[c2b0e10]268 * @param year Year (year 1900 = 0).
[1ab8539]269 * @param mon Month (January = 0).
[c2b0e10]270 * @param mday Day of month (first = 1).
[1ab8539]271 *
[c2b0e10]272 * @return Day of week (Sunday = 0).
[1ab8539]273 *
[c2b0e10]274 */
[1ab8539]275static time_t day_of_week(time_t year, time_t mon, time_t mday)
[c2b0e10]276{
277 /* 1970-01-01 is Thursday */
[1ab8539]278 return floor_mod(days_since_epoch(year, mon, mday) + 4, 7);
[c2b0e10]279}
280
[1ab8539]281/** Normalize the broken-down time.
282 *
283 * Optionally add specified amount of seconds.
284 *
[7f9d97f3]285 * @param tm Broken-down time to normalize.
[bd41ac52]286 * @param ts Timespec to add.
[1ab8539]287 *
[c2b0e10]288 * @return 0 on success, -1 on overflow
[1ab8539]289 *
[c2b0e10]290 */
[bd41ac52]291static int normalize_tm_ts(struct tm *tm, const struct timespec *ts)
[c2b0e10]292{
293 // TODO: DST correction
[a35b458]294
[c2b0e10]295 /* Set initial values. */
[bd41ac52]296 time_t nsec = tm->tm_nsec + ts->tv_nsec;
297 time_t sec = tm->tm_sec + ts->tv_sec;
[c2b0e10]298 time_t min = tm->tm_min;
299 time_t hour = tm->tm_hour;
300 time_t day = tm->tm_mday - 1;
301 time_t mon = tm->tm_mon;
302 time_t year = tm->tm_year;
[a35b458]303
[c2b0e10]304 /* Adjust time. */
[bd41ac52]305 sec += floor_div(nsec, NSECS_PER_SEC);
306 nsec = floor_mod(nsec, NSECS_PER_SEC);
[1ab8539]307 min += floor_div(sec, SECS_PER_MIN);
308 sec = floor_mod(sec, SECS_PER_MIN);
309 hour += floor_div(min, MINS_PER_HOUR);
310 min = floor_mod(min, MINS_PER_HOUR);
311 day += floor_div(hour, HOURS_PER_DAY);
312 hour = floor_mod(hour, HOURS_PER_DAY);
[a35b458]313
[c2b0e10]314 /* Adjust month. */
[1ab8539]315 year += floor_div(mon, 12);
316 mon = floor_mod(mon, 12);
[a35b458]317
[c2b0e10]318 /* Now the difficult part - days of month. */
[a35b458]319
[c2b0e10]320 /* First, deal with whole cycles of 400 years = 146097 days. */
[1ab8539]321 year += floor_div(day, 146097) * 400;
322 day = floor_mod(day, 146097);
[a35b458]323
[c2b0e10]324 /* Then, go in one year steps. */
325 if (mon <= 1) {
326 /* January and February. */
327 while (day > 365) {
[1ab8539]328 day -= is_leap_year(year) ? 366 : 365;
[c2b0e10]329 year++;
330 }
331 } else {
332 /* Rest of the year. */
333 while (day > 365) {
[1ab8539]334 day -= is_leap_year(year + 1) ? 366 : 365;
[c2b0e10]335 year++;
336 }
337 }
[a35b458]338
[c2b0e10]339 /* Finally, finish it off month per month. */
[1ab8539]340 while (day >= days_in_month(year, mon)) {
341 day -= days_in_month(year, mon);
[c2b0e10]342 mon++;
[a35b458]343
[c2b0e10]344 if (mon >= 12) {
345 mon -= 12;
346 year++;
347 }
348 }
[a35b458]349
[c2b0e10]350 /* Calculate the remaining two fields. */
[1ab8539]351 tm->tm_yday = day_of_year(year, mon, day + 1);
352 tm->tm_wday = day_of_week(year, mon, day + 1);
[a35b458]353
[c2b0e10]354 /* And put the values back to the struct. */
[bd41ac52]355 tm->tm_nsec = (int) nsec;
[c2b0e10]356 tm->tm_sec = (int) sec;
357 tm->tm_min = (int) min;
358 tm->tm_hour = (int) hour;
359 tm->tm_mday = (int) day + 1;
360 tm->tm_mon = (int) mon;
[a35b458]361
[1ab8539]362 /* Casts to work around POSIX brain-damage. */
363 if (year > ((int) INT_MAX) || year < ((int) INT_MIN)) {
364 tm->tm_year = (year < 0) ? ((int) INT_MIN) : ((int) INT_MAX);
[c2b0e10]365 return -1;
366 }
[a35b458]367
[c2b0e10]368 tm->tm_year = (int) year;
369 return 0;
370}
371
[7f9d97f3]372static int normalize_tm_time(struct tm *tm, time_t time)
373{
[bd41ac52]374 struct timespec ts = {
[7f9d97f3]375 .tv_sec = time,
[bd41ac52]376 .tv_nsec = 0
[7f9d97f3]377 };
378
[bd41ac52]379 return normalize_tm_ts(tm, &ts);
[7f9d97f3]380}
381
382
[1ab8539]383/** Which day the week-based year starts on.
384 *
385 * Relative to the first calendar day. E.g. if the year starts
386 * on December 31st, the return value is -1.
[c2b0e10]387 *
388 * @param Year since 1900.
[1ab8539]389 *
[c2b0e10]390 * @return Offset of week-based year relative to calendar year.
[1ab8539]391 *
[c2b0e10]392 */
[1ab8539]393static int wbyear_offset(int year)
[c2b0e10]394{
[1ab8539]395 int start_wday = day_of_week(year, 0, 1);
[a35b458]396
[1ab8539]397 return floor_mod(4 - start_wday, 7) - 3;
[c2b0e10]398}
399
[1ab8539]400/** Week-based year of the specified time.
[c2b0e10]401 *
402 * @param tm Normalized broken-down time.
[1ab8539]403 *
[c2b0e10]404 * @return Week-based year.
[1ab8539]405 *
[c2b0e10]406 */
[1ab8539]407static int wbyear(const struct tm *tm)
[c2b0e10]408{
[1ab8539]409 int day = tm->tm_yday - wbyear_offset(tm->tm_year);
[a35b458]410
[c2b0e10]411 if (day < 0) {
412 /* Last week of previous year. */
413 return tm->tm_year - 1;
414 }
[a35b458]415
[1ab8539]416 if (day > 364 + is_leap_year(tm->tm_year)) {
[c2b0e10]417 /* First week of next year. */
418 return tm->tm_year + 1;
419 }
[a35b458]420
[c2b0e10]421 /* All the other days are in the calendar year. */
422 return tm->tm_year;
423}
424
[1ab8539]425/** Week number of the year (assuming weeks start on Sunday).
426 *
[c2b0e10]427 * The first Sunday of January is the first day of week 1;
428 * days in the new year before this are in week 0.
429 *
430 * @param tm Normalized broken-down time.
[1ab8539]431 *
[c2b0e10]432 * @return The week number (0 - 53).
[1ab8539]433 *
[c2b0e10]434 */
[1ab8539]435static int sun_week_number(const struct tm *tm)
[c2b0e10]436{
[1ab8539]437 int first_day = (7 - day_of_week(tm->tm_year, 0, 1)) % 7;
[a35b458]438
[c2b0e10]439 return (tm->tm_yday - first_day + 7) / 7;
440}
441
[1ab8539]442/** Week number of the year (assuming weeks start on Monday).
443 *
444 * If the week containing January 1st has four or more days
445 * in the new year, then it is considered week 1. Otherwise,
446 * it is the last week of the previous year, and the next week
447 * is week 1. Both January 4th and the first Thursday
[c2b0e10]448 * of January are always in week 1.
449 *
450 * @param tm Normalized broken-down time.
[1ab8539]451 *
[c2b0e10]452 * @return The week number (1 - 53).
[1ab8539]453 *
[c2b0e10]454 */
[1ab8539]455static int iso_week_number(const struct tm *tm)
[c2b0e10]456{
[1ab8539]457 int day = tm->tm_yday - wbyear_offset(tm->tm_year);
[a35b458]458
[c2b0e10]459 if (day < 0) {
460 /* Last week of previous year. */
461 return 53;
462 }
[a35b458]463
[1ab8539]464 if (day > 364 + is_leap_year(tm->tm_year)) {
[c2b0e10]465 /* First week of next year. */
466 return 1;
467 }
[a35b458]468
[c2b0e10]469 /* All the other days give correct answer. */
470 return (day / 7 + 1);
471}
472
[1ab8539]473/** Week number of the year (assuming weeks start on Monday).
474 *
[c2b0e10]475 * The first Monday of January is the first day of week 1;
[1ab8539]476 * days in the new year before this are in week 0.
[c2b0e10]477 *
478 * @param tm Normalized broken-down time.
[1ab8539]479 *
[c2b0e10]480 * @return The week number (0 - 53).
[1ab8539]481 *
[c2b0e10]482 */
[1ab8539]483static int mon_week_number(const struct tm *tm)
[c2b0e10]484{
[1ab8539]485 int first_day = (1 - day_of_week(tm->tm_year, 0, 1)) % 7;
[a35b458]486
[c2b0e10]487 return (tm->tm_yday - first_day + 7) / 7;
488}
489
[bd41ac52]490static void ts_normalize(struct timespec *ts)
[7f9d97f3]491{
[bd41ac52]492 while (ts->tv_nsec >= NSECS_PER_SEC) {
493 ts->tv_sec++;
494 ts->tv_nsec -= NSECS_PER_SEC;
[7f9d97f3]495 }
[bd41ac52]496 while (ts->tv_nsec < 0) {
497 ts->tv_sec--;
498 ts->tv_nsec += NSECS_PER_SEC;
[7f9d97f3]499 }
500}
501
[bd41ac52]502/** Add nanoseconds to given timespec.
[daa90e8]503 *
[bd41ac52]504 * @param ts Destination timespec.
505 * @param nsecs Number of nanoseconds to add.
[2c577e0b]506 *
[daa90e8]507 */
[bd41ac52]508void ts_add_diff(struct timespec *ts, nsec_t nsecs)
[daa90e8]509{
[bd41ac52]510 ts->tv_sec += nsecs / NSECS_PER_SEC;
511 ts->tv_nsec += nsecs % NSECS_PER_SEC;
512 ts_normalize(ts);
[7f9d97f3]513}
514
[bd41ac52]515/** Add two timespecs.
[7f9d97f3]516 *
[bd41ac52]517 * @param ts1 First timespec.
518 * @param ts2 Second timespec.
[7f9d97f3]519 */
[bd41ac52]520void ts_add(struct timespec *ts1, const struct timespec *ts2)
[7f9d97f3]521{
[bd41ac52]522 ts1->tv_sec += ts2->tv_sec;
523 ts1->tv_nsec += ts2->tv_nsec;
524 ts_normalize(ts1);
[daa90e8]525}
526
[bd41ac52]527/** Subtract two timespecs.
[daa90e8]528 *
[bd41ac52]529 * @param ts1 First timespec.
530 * @param ts2 Second timespec.
[2c577e0b]531 *
[bd41ac52]532 * @return Difference between ts1 and ts2 (ts1 - ts2) in nanoseconds.
[daa90e8]533 *
534 */
[bd41ac52]535nsec_t ts_sub_diff(const struct timespec *ts1, const struct timespec *ts2)
[daa90e8]536{
[bd41ac52]537 return (nsec_t) (ts1->tv_nsec - ts2->tv_nsec) +
538 SEC2NSEC((ts1->tv_sec - ts2->tv_sec));
[7f9d97f3]539}
540
[bd41ac52]541/** Subtract two timespecs.
[7f9d97f3]542 *
[bd41ac52]543 * @param ts1 First timespec.
544 * @param ts2 Second timespec.
[7f9d97f3]545 *
546 */
[bd41ac52]547void ts_sub(struct timespec *ts1, const struct timespec *ts2)
[7f9d97f3]548{
[bd41ac52]549 ts1->tv_sec -= ts2->tv_sec;
550 ts1->tv_nsec -= ts2->tv_nsec;
551 ts_normalize(ts1);
[daa90e8]552}
553
[bd41ac52]554/** Decide if one timespec is greater than the other.
[daa90e8]555 *
[bd41ac52]556 * @param ts1 First timespec.
557 * @param ts2 Second timespec.
[2c577e0b]558 *
[bd41ac52]559 * @return True if ts1 is greater than ts2.
560 * @return False otherwise.
[daa90e8]561 *
562 */
[bd41ac52]563bool ts_gt(const struct timespec *ts1, const struct timespec *ts2)
[daa90e8]564{
[bd41ac52]565 if (ts1->tv_sec > ts2->tv_sec)
[2c577e0b]566 return true;
[a35b458]567
[bd41ac52]568 if ((ts1->tv_sec == ts2->tv_sec) && (ts1->tv_nsec > ts2->tv_nsec))
[2c577e0b]569 return true;
[a35b458]570
[2c577e0b]571 return false;
[daa90e8]572}
573
[bd41ac52]574/** Decide if one timespec is greater than or equal to the other.
[daa90e8]575 *
[bd41ac52]576 * @param ts1 First timespec.
577 * @param ts2 Second timespec.
[2c577e0b]578 *
[bd41ac52]579 * @return True if ts1 is greater than or equal to ts2.
580 * @return False otherwise.
[daa90e8]581 *
582 */
[bd41ac52]583bool ts_gteq(const struct timespec *ts1, const struct timespec *ts2)
[daa90e8]584{
[bd41ac52]585 if (ts1->tv_sec > ts2->tv_sec)
[2c577e0b]586 return true;
[a35b458]587
[bd41ac52]588 if ((ts1->tv_sec == ts2->tv_sec) && (ts1->tv_nsec >= ts2->tv_nsec))
[2c577e0b]589 return true;
[a35b458]590
[2c577e0b]591 return false;
[daa90e8]592}
593
[bd41ac52]594/** Get real time from a RTC service.
[2c577e0b]595 *
[bd41ac52]596 * @param[out] ts Timespec to hold time read from the RTC service (if
597 * available). If no such service exists, the returned time
598 * corresponds to system uptime.
[0b99e40]599 */
[bd41ac52]600void getrealtime(struct timespec *ts)
[3a58347]601{
602 if (clock_conn == NULL) {
[1ab8539]603 category_id_t cat_id;
[b7fd2a0]604 errno_t rc = loc_category_get_id("clock", &cat_id, IPC_FLAG_BLOCKING);
[3a58347]605 if (rc != EOK)
[1ab8539]606 goto fallback;
[a35b458]607
[1ab8539]608 service_id_t *svc_ids;
609 size_t svc_cnt;
[3a58347]610 rc = loc_category_get_svcs(cat_id, &svc_ids, &svc_cnt);
611 if (rc != EOK)
[1ab8539]612 goto fallback;
[a35b458]613
[3a58347]614 if (svc_cnt == 0)
[1ab8539]615 goto fallback;
[a35b458]616
[1ab8539]617 char *svc_name;
[3a58347]618 rc = loc_service_get_name(svc_ids[0], &svc_name);
[1ab8539]619 free(svc_ids);
[3a58347]620 if (rc != EOK)
[1ab8539]621 goto fallback;
[a35b458]622
[1ab8539]623 service_id_t svc_id;
[3a58347]624 rc = loc_service_get_id(svc_name, &svc_id, 0);
[1ab8539]625 free(svc_name);
[3a58347]626 if (rc != EOK)
[1ab8539]627 goto fallback;
[a35b458]628
[f9b2cb4c]629 clock_conn = loc_service_connect(svc_id, INTERFACE_DDF,
630 IPC_FLAG_BLOCKING);
[3a58347]631 if (!clock_conn)
[1ab8539]632 goto fallback;
[3a58347]633 }
[a35b458]634
[1ab8539]635 struct tm time;
[b7fd2a0]636 errno_t rc = clock_dev_time_get(clock_conn, &time);
[3a58347]637 if (rc != EOK)
[1ab8539]638 goto fallback;
[a35b458]639
[bd41ac52]640 ts->tv_nsec = time.tm_nsec;
641 ts->tv_sec = mktime(&time);
[a35b458]642
[1ab8539]643 return;
[a35b458]644
[1ab8539]645fallback:
[bd41ac52]646 getuptime(ts);
[3a58347]647}
648
[bd41ac52]649/** Get system uptime.
650 *
651 * @param[out] ts Timespec to hold time current uptime.
652 *
653 * The time variables are memory mapped (read-only) from kernel which
654 * updates them periodically.
655 *
656 * As it is impossible to read 2 values atomically, we use a trick:
657 * First we read the seconds, then we read the microseconds, then we
658 * read the seconds again. If a second elapsed in the meantime, set
659 * the microseconds to zero.
660 *
661 * This assures that the values returned by two subsequent calls
662 * to getuptime() are monotonous.
663 *
664 */
665void getuptime(struct timespec *ts)
[0b99e40]666{
[6119f24]667 if (ktime == NULL) {
668 uintptr_t faddr;
[b7fd2a0]669 errno_t rc = sysinfo_get_value("clock.faddr", &faddr);
[6119f24]670 if (rc != EOK) {
671 errno = rc;
[1ab8539]672 goto fallback;
[6119f24]673 }
[a35b458]674
[bf9cb2f]675 void *addr = AS_AREA_ANY;
[8442d10]676 rc = physmem_map(faddr, 1, AS_AREA_READ | AS_AREA_CACHEABLE,
677 &addr);
[6119f24]678 if (rc != EOK) {
679 as_area_destroy(addr);
680 errno = rc;
[1ab8539]681 goto fallback;
[6119f24]682 }
[a35b458]683
[6119f24]684 ktime = addr;
[0b99e40]685 }
[a35b458]686
[2c577e0b]687 sysarg_t s2 = ktime->seconds2;
[a35b458]688
[5bd03eb]689 read_barrier();
[bd41ac52]690 ts->tv_nsec = USEC2NSEC(ktime->useconds);
[a35b458]691
[0b99e40]692 read_barrier();
[2c577e0b]693 sysarg_t s1 = ktime->seconds1;
[a35b458]694
[2d1fde3b]695 if (s1 != s2) {
[bd41ac52]696 ts->tv_sec = max(s1, s2);
697 ts->tv_nsec = 0;
[2d1fde3b]698 } else
[bd41ac52]699 ts->tv_sec = s1;
[a35b458]700
[1ab8539]701 return;
[a35b458]702
[1ab8539]703fallback:
[bd41ac52]704 ts->tv_sec = 0;
705 ts->tv_nsec = 0;
[0b99e40]706}
[44c6d88d]707
[813a703]708time_t time(time_t *tloc)
709{
[bd41ac52]710 struct timespec ts;
711 getrealtime(&ts);
[a35b458]712
[813a703]713 if (tloc)
[bd41ac52]714 *tloc = ts.tv_sec;
[a35b458]715
[bd41ac52]716 return ts.tv_sec;
[813a703]717}
718
[bd41ac52]719void udelay(sysarg_t time)
[5fd3f2d]720{
721 (void) __SYSCALL1(SYS_THREAD_UDELAY, (sysarg_t) time);
722}
723
[1ab8539]724/** Get time from broken-down time.
725 *
726 * First normalize the provided broken-down time
727 * (moves all values to their proper bounds) and
728 * then try to calculate the appropriate time_t
729 * representation.
[c2b0e10]730 *
731 * @param tm Broken-down time.
[1ab8539]732 *
733 * @return time_t representation of the time.
734 * @return Undefined value on overflow.
735 *
[c2b0e10]736 */
737time_t mktime(struct tm *tm)
738{
739 // TODO: take DST flag into account
740 // TODO: detect overflow
[a35b458]741
[7f9d97f3]742 normalize_tm_time(tm, 0);
[1ab8539]743 return secs_since_epoch(tm);
[c2b0e10]744}
745
[1ab8539]746/*
747 * FIXME: This requires POSIX-correct snprintf.
748 * Otherwise it won't work with non-ASCII chars.
749 */
750#define APPEND(...) \
751 { \
752 consumed = snprintf(ptr, remaining, __VA_ARGS__); \
753 if (consumed >= remaining) \
754 return 0; \
755 \
756 ptr += consumed; \
757 remaining -= consumed; \
758 }
759
760#define RECURSE(fmt) \
761 { \
762 consumed = strftime(ptr, remaining, fmt, tm); \
763 if (consumed == 0) \
764 return 0; \
765 \
766 ptr += consumed; \
767 remaining -= consumed; \
768 }
769
770#define TO_12H(hour) \
771 (((hour) > 12) ? ((hour) - 12) : \
772 (((hour) == 0) ? 12 : (hour)))
773
774/** Convert time and date to a string.
775 *
776 * @param s Buffer to write string to.
[c2b0e10]777 * @param maxsize Size of the buffer.
[1ab8539]778 * @param format Format of the output.
779 * @param tm Broken-down time to format.
780 *
[c2b0e10]781 * @return Number of bytes written.
[1ab8539]782 *
[c2b0e10]783 */
784size_t strftime(char *restrict s, size_t maxsize,
785 const char *restrict format, const struct tm *restrict tm)
786{
787 assert(s != NULL);
788 assert(format != NULL);
789 assert(tm != NULL);
[a35b458]790
[c2b0e10]791 // TODO: use locale
[a35b458]792
[c2b0e10]793 static const char *wday_abbr[] = {
794 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
795 };
[a35b458]796
[c2b0e10]797 static const char *wday[] = {
798 "Sunday", "Monday", "Tuesday", "Wednesday",
799 "Thursday", "Friday", "Saturday"
800 };
[a35b458]801
[c2b0e10]802 static const char *mon_abbr[] = {
803 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
804 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
805 };
[a35b458]806
[c2b0e10]807 static const char *mon[] = {
808 "January", "February", "March", "April", "May", "June", "July",
809 "August", "September", "October", "November", "December"
810 };
[a35b458]811
[1ab8539]812 if (maxsize < 1)
[c2b0e10]813 return 0;
[a35b458]814
[c2b0e10]815 char *ptr = s;
816 size_t consumed;
817 size_t remaining = maxsize;
[a35b458]818
[c2b0e10]819 while (*format != '\0') {
820 if (*format != '%') {
[1ab8539]821 APPEND("%c", *format);
[c2b0e10]822 format++;
823 continue;
824 }
[a35b458]825
[c2b0e10]826 format++;
[1ab8539]827 if ((*format == '0') || (*format == '+')) {
[c2b0e10]828 // TODO: padding
829 format++;
830 }
[a35b458]831
[c2b0e10]832 while (isdigit(*format)) {
833 // TODO: padding
834 format++;
835 }
[a35b458]836
[1ab8539]837 if ((*format == 'O') || (*format == 'E')) {
[c2b0e10]838 // TODO: locale's alternative format
839 format++;
840 }
[a35b458]841
[c2b0e10]842 switch (*format) {
843 case 'a':
[1ab8539]844 APPEND("%s", wday_abbr[tm->tm_wday]);
845 break;
[c2b0e10]846 case 'A':
[1ab8539]847 APPEND("%s", wday[tm->tm_wday]);
848 break;
[c2b0e10]849 case 'b':
[1ab8539]850 APPEND("%s", mon_abbr[tm->tm_mon]);
851 break;
[c2b0e10]852 case 'B':
[1ab8539]853 APPEND("%s", mon[tm->tm_mon]);
854 break;
[c2b0e10]855 case 'c':
856 // TODO: locale-specific datetime format
[1ab8539]857 RECURSE("%Y-%m-%d %H:%M:%S");
858 break;
[c2b0e10]859 case 'C':
[1ab8539]860 APPEND("%02d", (1900 + tm->tm_year) / 100);
861 break;
[c2b0e10]862 case 'd':
[1ab8539]863 APPEND("%02d", tm->tm_mday);
864 break;
[c2b0e10]865 case 'D':
[1ab8539]866 RECURSE("%m/%d/%y");
867 break;
[c2b0e10]868 case 'e':
[1ab8539]869 APPEND("%2d", tm->tm_mday);
870 break;
[c2b0e10]871 case 'F':
[1ab8539]872 RECURSE("%+4Y-%m-%d");
873 break;
[c2b0e10]874 case 'g':
[1ab8539]875 APPEND("%02d", wbyear(tm) % 100);
876 break;
[c2b0e10]877 case 'G':
[1ab8539]878 APPEND("%d", wbyear(tm));
879 break;
[c2b0e10]880 case 'h':
[1ab8539]881 RECURSE("%b");
882 break;
[c2b0e10]883 case 'H':
[1ab8539]884 APPEND("%02d", tm->tm_hour);
885 break;
[c2b0e10]886 case 'I':
[1ab8539]887 APPEND("%02d", TO_12H(tm->tm_hour));
888 break;
[c2b0e10]889 case 'j':
[1ab8539]890 APPEND("%03d", tm->tm_yday);
891 break;
[c2b0e10]892 case 'k':
[1ab8539]893 APPEND("%2d", tm->tm_hour);
894 break;
[c2b0e10]895 case 'l':
[1ab8539]896 APPEND("%2d", TO_12H(tm->tm_hour));
897 break;
[c2b0e10]898 case 'm':
[1ab8539]899 APPEND("%02d", tm->tm_mon);
900 break;
[c2b0e10]901 case 'M':
[1ab8539]902 APPEND("%02d", tm->tm_min);
903 break;
[c2b0e10]904 case 'n':
[1ab8539]905 APPEND("\n");
906 break;
[c2b0e10]907 case 'p':
[1ab8539]908 APPEND("%s", tm->tm_hour < 12 ? "AM" : "PM");
909 break;
[c2b0e10]910 case 'P':
[1ab8539]911 APPEND("%s", tm->tm_hour < 12 ? "am" : "PM");
912 break;
[c2b0e10]913 case 'r':
[1ab8539]914 RECURSE("%I:%M:%S %p");
915 break;
[c2b0e10]916 case 'R':
[1ab8539]917 RECURSE("%H:%M");
918 break;
[c2b0e10]919 case 's':
[bd41ac52]920 APPEND("%lld", secs_since_epoch(tm));
[1ab8539]921 break;
[c2b0e10]922 case 'S':
[1ab8539]923 APPEND("%02d", tm->tm_sec);
924 break;
[c2b0e10]925 case 't':
[1ab8539]926 APPEND("\t");
927 break;
[c2b0e10]928 case 'T':
[1ab8539]929 RECURSE("%H:%M:%S");
930 break;
[c2b0e10]931 case 'u':
[1ab8539]932 APPEND("%d", (tm->tm_wday == 0) ? 7 : tm->tm_wday);
[c2b0e10]933 break;
934 case 'U':
[1ab8539]935 APPEND("%02d", sun_week_number(tm));
936 break;
[c2b0e10]937 case 'V':
[1ab8539]938 APPEND("%02d", iso_week_number(tm));
939 break;
[c2b0e10]940 case 'w':
[1ab8539]941 APPEND("%d", tm->tm_wday);
942 break;
[c2b0e10]943 case 'W':
[1ab8539]944 APPEND("%02d", mon_week_number(tm));
945 break;
[c2b0e10]946 case 'x':
947 // TODO: locale-specific date format
[1ab8539]948 RECURSE("%Y-%m-%d");
949 break;
[c2b0e10]950 case 'X':
951 // TODO: locale-specific time format
[1ab8539]952 RECURSE("%H:%M:%S");
953 break;
[c2b0e10]954 case 'y':
[1ab8539]955 APPEND("%02d", tm->tm_year % 100);
956 break;
[c2b0e10]957 case 'Y':
[1ab8539]958 APPEND("%d", 1900 + tm->tm_year);
959 break;
[c2b0e10]960 case 'z':
961 // TODO: timezone
962 break;
963 case 'Z':
964 // TODO: timezone
965 break;
966 case '%':
[1ab8539]967 APPEND("%%");
[c2b0e10]968 break;
969 default:
970 /* Invalid specifier, print verbatim. */
[1ab8539]971 while (*format != '%')
[c2b0e10]972 format--;
[a35b458]973
[1ab8539]974 APPEND("%%");
[c2b0e10]975 break;
976 }
[a35b458]977
[c2b0e10]978 format++;
979 }
[a35b458]980
[c2b0e10]981 return maxsize - remaining;
982}
983
[1ab8539]984/** Convert a time value to a broken-down UTC time/
[f7ea5400]985 *
[1ab8539]986 * @param time Time to convert
987 * @param result Structure to store the result to
988 *
[cde999a]989 * @return EOK or an error code
[f7ea5400]990 *
991 */
[b7fd2a0]992errno_t time_utc2tm(const time_t time, struct tm *restrict result)
[f7ea5400]993{
994 assert(result != NULL);
[a35b458]995
[5b3394c]996 /* Set result to epoch. */
[bd41ac52]997 result->tm_nsec = 0;
[f7ea5400]998 result->tm_sec = 0;
999 result->tm_min = 0;
1000 result->tm_hour = 0;
1001 result->tm_mday = 1;
1002 result->tm_mon = 0;
1003 result->tm_year = 70; /* 1970 */
[a35b458]1004
[7f9d97f3]1005 if (normalize_tm_time(result, time) == -1)
[f7ea5400]1006 return EOVERFLOW;
[a35b458]1007
[f7ea5400]1008 return EOK;
[5b3394c]1009}
1010
[1ab8539]1011/** Convert a time value to a NULL-terminated string.
1012 *
1013 * The format is "Wed Jun 30 21:49:08 1993\n" expressed in UTC.
1014 *
1015 * @param time Time to convert.
1016 * @param buf Buffer to store the string to, must be at least
1017 * ASCTIME_BUF_LEN bytes long.
[f7ea5400]1018 *
[cde999a]1019 * @return EOK or an error code.
[f7ea5400]1020 *
1021 */
[b7fd2a0]1022errno_t time_utc2str(const time_t time, char *restrict buf)
[f7ea5400]1023{
[1ab8539]1024 struct tm tm;
[b7fd2a0]1025 errno_t ret = time_utc2tm(time, &tm);
[1ab8539]1026 if (ret != EOK)
1027 return ret;
[a35b458]1028
[1ab8539]1029 time_tm2str(&tm, buf);
[f7ea5400]1030 return EOK;
1031}
1032
[1ab8539]1033/** Convert broken-down time to a NULL-terminated string.
1034 *
1035 * The format is "Sun Jan 1 00:00:00 1970\n". (Obsolete)
[8219eb9]1036 *
1037 * @param timeptr Broken-down time structure.
[1ab8539]1038 * @param buf Buffer to store string to, must be at least
1039 * ASCTIME_BUF_LEN bytes long.
1040 *
[8219eb9]1041 */
[664fc031]1042void time_tm2str(const struct tm *restrict timeptr, char *restrict buf)
[8219eb9]1043{
1044 assert(timeptr != NULL);
[f7ea5400]1045 assert(buf != NULL);
[a35b458]1046
[8219eb9]1047 static const char *wday[] = {
1048 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
1049 };
[a35b458]1050
[8219eb9]1051 static const char *mon[] = {
1052 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1053 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1054 };
[a35b458]1055
[8219eb9]1056 snprintf(buf, ASCTIME_BUF_LEN, "%s %s %2d %02d:%02d:%02d %d\n",
1057 wday[timeptr->tm_wday],
1058 mon[timeptr->tm_mon],
1059 timeptr->tm_mday, timeptr->tm_hour,
1060 timeptr->tm_min, timeptr->tm_sec,
1061 1900 + timeptr->tm_year);
1062}
1063
[1ab8539]1064/** Converts a time value to a broken-down local time.
1065 *
1066 * Time is expressed relative to the user's specified timezone.
[f7ea5400]1067 *
[7f9d97f3]1068 * @param tv Timeval to convert.
[1ab8539]1069 * @param result Structure to store the result to.
1070 *
[cde999a]1071 * @return EOK on success or an error code.
[f6cb995]1072 *
1073 */
[bd41ac52]1074errno_t time_ts2tm(const struct timespec *ts, struct tm *restrict result)
[f6cb995]1075{
[1ab8539]1076 // TODO: Deal with timezones.
1077 // Currently assumes system and all times are in UTC
[a35b458]1078
[f6cb995]1079 /* Set result to epoch. */
[bd41ac52]1080 result->tm_nsec = 0;
[f7ea5400]1081 result->tm_sec = 0;
1082 result->tm_min = 0;
1083 result->tm_hour = 0;
1084 result->tm_mday = 1;
1085 result->tm_mon = 0;
1086 result->tm_year = 70; /* 1970 */
[a35b458]1087
[bd41ac52]1088 if (normalize_tm_ts(result, ts) == -1)
[f7ea5400]1089 return EOVERFLOW;
[a35b458]1090
[f7ea5400]1091 return EOK;
[f6cb995]1092}
[c2b0e10]1093
[7f9d97f3]1094/** Converts a time value to a broken-down local time.
1095 *
1096 * Time is expressed relative to the user's specified timezone.
1097 *
1098 * @param timer Time to convert.
1099 * @param result Structure to store the result to.
1100 *
[cde999a]1101 * @return EOK on success or an error code.
[7f9d97f3]1102 *
1103 */
[b7fd2a0]1104errno_t time_local2tm(const time_t time, struct tm *restrict result)
[7f9d97f3]1105{
[bd41ac52]1106 struct timespec ts = {
[7f9d97f3]1107 .tv_sec = time,
[bd41ac52]1108 .tv_nsec = 0
[7f9d97f3]1109 };
1110
[bd41ac52]1111 return time_ts2tm(&ts, result);
[7f9d97f3]1112}
1113
[1ab8539]1114/** Convert the calendar time to a NULL-terminated string.
1115 *
1116 * The format is "Wed Jun 30 21:49:08 1993\n" expressed relative to the
[f7ea5400]1117 * user's specified timezone.
1118 *
[1ab8539]1119 * @param timer Time to convert.
1120 * @param buf Buffer to store the string to. Must be at least
1121 * ASCTIME_BUF_LEN bytes long.
1122 *
[cde999a]1123 * @return EOK on success or an error code.
[1ab8539]1124 *
[56b308e]1125 */
[b7fd2a0]1126errno_t time_local2str(const time_t time, char *buf)
[56b308e]1127{
[f7ea5400]1128 struct tm loctime;
[b7fd2a0]1129 errno_t ret = time_local2tm(time, &loctime);
[1ab8539]1130 if (ret != EOK)
1131 return ret;
[a35b458]1132
[664fc031]1133 time_tm2str(&loctime, buf);
[f7ea5400]1134 return EOK;
[56b308e]1135}
1136
[1ab8539]1137/** Calculate the difference between two times, in seconds.
1138 *
[d3e3a71]1139 * @param time1 First time.
1140 * @param time0 Second time.
[1ab8539]1141 *
1142 * @return Time difference in seconds.
1143 *
[d3e3a71]1144 */
1145double difftime(time_t time1, time_t time0)
1146{
1147 return (double) (time1 - time0);
1148}
1149
[a46da63]1150/** @}
[b2951e2]1151 */
Note: See TracBrowser for help on using the repository browser.