source: mainline/uspace/lib/c/generic/time.c@ 034ce6bb

serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 034ce6bb was 5fc8244, checked in by Jiri Svoboda <jiri@…>, 4 years ago

Move device-related stuff out of libc to libdevice

Unfortunately, we need to keep clock_dev, which pulls in hw_res
and pio_window. clock_dev is used by time.c

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