source: mainline/uspace/lib/c/generic/time.c@ 889cdb1

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 889cdb1 was 3f7fe9e, checked in by Jiří Zárevúcky <jiri.zarevucky@…>, 7 years ago

Clean up headers

Depends on <limits.h> and <stdint.h> being provided, which is a step up from
depending on mostly undocumented predefined macros.
In principle, <limits.h> and <stdint.h> mostly describe properties of
the compiler, so even though we depend on certain values for their contents,
actually defining them in the library is kind of reversal of concerns.

  • 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>
49#include <ctype.h>
[f7e69f5]50#include <assert.h>
[3a58347]51#include <loc.h>
52#include <device/clock_dev.h>
[bd41ac52]53#include <stats.h>
[c61d34b]54
[58e7b26]55#define ASCTIME_BUF_LEN 27
[1ab8539]56
57#define HOURS_PER_DAY 24
58#define MINS_PER_HOUR 60
59#define SECS_PER_MIN 60
[bd41ac52]60#define NSECS_PER_SEC 1000000000ll
[1ab8539]61#define MINS_PER_DAY (MINS_PER_HOUR * HOURS_PER_DAY)
62#define SECS_PER_HOUR (SECS_PER_MIN * MINS_PER_HOUR)
63#define SECS_PER_DAY (SECS_PER_HOUR * HOURS_PER_DAY)
[8219eb9]64
[2c577e0b]65/** Pointer to kernel shared variables with time */
[0b99e40]66struct {
[2d1fde3b]67 volatile sysarg_t seconds1;
[0b99e40]68 volatile sysarg_t useconds;
[2d1fde3b]69 volatile sysarg_t seconds2;
[0b99e40]70} *ktime = NULL;
71
[1ab8539]72static async_sess_t *clock_conn = NULL;
[c2b0e10]73
[bd41ac52]74/**
75 * Get CPU time used since the process invocation.
76 *
77 * @return Consumed microseconds by this process or -1 if not available.
78 */
79clock_t clock(void)
80{
81 static_assert(CLOCKS_PER_SEC == 1000000);
82
83 size_t count;
84 stats_cpu_t *cpu_stats = stats_get_cpus(&count);
85 if (!cpu_stats)
86 return (clock_t) -1;
87 if (!cpu_stats->frequency_mhz) {
88 free(cpu_stats);
89 return (clock_t) -1;
90 }
91
92 clock_t total_usecs = -1;
93 if (cpu_stats) {
94 stats_task_t *task_stats = stats_get_task(task_get_id());
95 if (task_stats) {
96 total_usecs = (clock_t) (task_stats->kcycles +
97 task_stats->ucycles) / cpu_stats->frequency_mhz;
98 free(task_stats);
99 }
100 free(cpu_stats);
101 }
102
103 return total_usecs;
104}
105
[1ab8539]106/** Check whether the year is a leap year.
[c2b0e10]107 *
108 * @param year Year since 1900 (e.g. for 1970, the value is 70).
[1ab8539]109 *
[c2b0e10]110 * @return true if year is a leap year, false otherwise
[1ab8539]111 *
[c2b0e10]112 */
[1ab8539]113static bool is_leap_year(time_t year)
[c2b0e10]114{
115 year += 1900;
[a35b458]116
[c2b0e10]117 if (year % 400 == 0)
118 return true;
[a35b458]119
[c2b0e10]120 if (year % 100 == 0)
121 return false;
[a35b458]122
[c2b0e10]123 if (year % 4 == 0)
124 return true;
[a35b458]125
[c2b0e10]126 return false;
127}
128
[1ab8539]129/** How many days there are in the given month
130 *
131 * Return how many days there are in the given month of the given year.
[c2b0e10]132 * Note that year is only taken into account if month is February.
133 *
134 * @param year Year since 1900 (can be negative).
[1ab8539]135 * @param mon Month of the year. 0 for January, 11 for December.
136 *
[c2b0e10]137 * @return Number of days in the specified month.
[1ab8539]138 *
[c2b0e10]139 */
[1ab8539]140static int days_in_month(time_t year, time_t mon)
[c2b0e10]141{
[1ab8539]142 assert(mon >= 0);
143 assert(mon <= 11);
[a35b458]144
[1ab8539]145 static int month_days[] = {
146 31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
147 };
[a35b458]148
[c2b0e10]149 if (mon == 1) {
[1ab8539]150 /* February */
[c2b0e10]151 year += 1900;
[1ab8539]152 return is_leap_year(year) ? 29 : 28;
[c2b0e10]153 }
[a35b458]154
[1ab8539]155 return month_days[mon];
[c2b0e10]156}
157
[1ab8539]158/** Which day of that year it is.
159 *
160 * For specified year, month and day of month, return which day of that year
[c2b0e10]161 * it is.
162 *
163 * For example, given date 2011-01-03, the corresponding expression is:
[1ab8539]164 * day_of_year(111, 0, 3) == 2
[c2b0e10]165 *
166 * @param year Year (year 1900 = 0, can be negative).
[1ab8539]167 * @param mon Month (January = 0).
[c2b0e10]168 * @param mday Day of month (First day is 1).
[1ab8539]169 *
[c2b0e10]170 * @return Day of year (First day is 0).
[1ab8539]171 *
[c2b0e10]172 */
[1ab8539]173static int day_of_year(time_t year, time_t mon, time_t mday)
[c2b0e10]174{
[1ab8539]175 static int mdays[] = {
176 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
177 };
[a35b458]178
[1ab8539]179 static int leap_mdays[] = {
180 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335
181 };
[a35b458]182
[1ab8539]183 return (is_leap_year(year) ? leap_mdays[mon] : mdays[mon]) + mday - 1;
[c2b0e10]184}
185
[1ab8539]186/** Integer division that rounds to negative infinity.
187 *
188 * Used by some functions in this module.
[c2b0e10]189 *
190 * @param op1 Dividend.
191 * @param op2 Divisor.
[1ab8539]192 *
[c2b0e10]193 * @return Rounded quotient.
[1ab8539]194 *
[c2b0e10]195 */
[1ab8539]196static time_t floor_div(time_t op1, time_t op2)
[c2b0e10]197{
[1ab8539]198 if ((op1 >= 0) || (op1 % op2 == 0))
[c2b0e10]199 return op1 / op2;
[a35b458]200
[1ab8539]201 return op1 / op2 - 1;
[c2b0e10]202}
203
[1ab8539]204/** Modulo that rounds to negative infinity.
205 *
206 * Used by some functions in this module.
[c2b0e10]207 *
208 * @param op1 Dividend.
209 * @param op2 Divisor.
[1ab8539]210 *
[c2b0e10]211 * @return Remainder.
[1ab8539]212 *
[c2b0e10]213 */
[1ab8539]214static time_t floor_mod(time_t op1, time_t op2)
[c2b0e10]215{
[1ab8539]216 time_t div = floor_div(op1, op2);
[a35b458]217
[1ab8539]218 /*
219 * (a / b) * b + a % b == a
220 * Thus: a % b == a - (a / b) * b
221 */
[a35b458]222
[1ab8539]223 time_t result = op1 - div * op2;
[a35b458]224
[1ab8539]225 /* Some paranoid checking to ensure there is mistake here. */
[c2b0e10]226 assert(result >= 0);
227 assert(result < op2);
228 assert(div * op2 + result == op1);
[a35b458]229
[c2b0e10]230 return result;
231}
232
[1ab8539]233/** Number of days since the Epoch.
234 *
[c2b0e10]235 * Epoch is 1970-01-01, which is also equal to day 0.
236 *
237 * @param year Year (year 1900 = 0, may be negative).
[1ab8539]238 * @param mon Month (January = 0).
[c2b0e10]239 * @param mday Day of month (first day = 1).
[1ab8539]240 *
[c2b0e10]241 * @return Number of days since the Epoch.
[1ab8539]242 *
[c2b0e10]243 */
[1ab8539]244static time_t days_since_epoch(time_t year, time_t mon, time_t mday)
[c2b0e10]245{
[1ab8539]246 return (year - 70) * 365 + floor_div(year - 69, 4) -
247 floor_div(year - 1, 100) + floor_div(year + 299, 400) +
248 day_of_year(year, mon, mday);
[c2b0e10]249}
250
[1ab8539]251/** Seconds since the Epoch.
252 *
253 * See also days_since_epoch().
254 *
[c2b0e10]255 * @param tm Normalized broken-down time.
[1ab8539]256 *
[c2b0e10]257 * @return Number of seconds since the epoch, not counting leap seconds.
[1ab8539]258 *
[c2b0e10]259 */
[1ab8539]260static time_t secs_since_epoch(const struct tm *tm)
[c2b0e10]261{
[1ab8539]262 return days_since_epoch(tm->tm_year, tm->tm_mon, tm->tm_mday) *
[c2b0e10]263 SECS_PER_DAY + tm->tm_hour * SECS_PER_HOUR +
264 tm->tm_min * SECS_PER_MIN + tm->tm_sec;
265}
266
[1ab8539]267/** Which day of week the specified date is.
268 *
[c2b0e10]269 * @param year Year (year 1900 = 0).
[1ab8539]270 * @param mon Month (January = 0).
[c2b0e10]271 * @param mday Day of month (first = 1).
[1ab8539]272 *
[c2b0e10]273 * @return Day of week (Sunday = 0).
[1ab8539]274 *
[c2b0e10]275 */
[1ab8539]276static time_t day_of_week(time_t year, time_t mon, time_t mday)
[c2b0e10]277{
278 /* 1970-01-01 is Thursday */
[1ab8539]279 return floor_mod(days_since_epoch(year, mon, mday) + 4, 7);
[c2b0e10]280}
281
[1ab8539]282/** Normalize the broken-down time.
283 *
284 * Optionally add specified amount of seconds.
285 *
[7f9d97f3]286 * @param tm Broken-down time to normalize.
[bd41ac52]287 * @param ts Timespec to add.
[1ab8539]288 *
[c2b0e10]289 * @return 0 on success, -1 on overflow
[1ab8539]290 *
[c2b0e10]291 */
[bd41ac52]292static int normalize_tm_ts(struct tm *tm, const struct timespec *ts)
[c2b0e10]293{
294 // TODO: DST correction
[a35b458]295
[c2b0e10]296 /* Set initial values. */
[bd41ac52]297 time_t nsec = tm->tm_nsec + ts->tv_nsec;
298 time_t sec = tm->tm_sec + ts->tv_sec;
[c2b0e10]299 time_t min = tm->tm_min;
300 time_t hour = tm->tm_hour;
301 time_t day = tm->tm_mday - 1;
302 time_t mon = tm->tm_mon;
303 time_t year = tm->tm_year;
[a35b458]304
[c2b0e10]305 /* Adjust time. */
[bd41ac52]306 sec += floor_div(nsec, NSECS_PER_SEC);
307 nsec = floor_mod(nsec, NSECS_PER_SEC);
[1ab8539]308 min += floor_div(sec, SECS_PER_MIN);
309 sec = floor_mod(sec, SECS_PER_MIN);
310 hour += floor_div(min, MINS_PER_HOUR);
311 min = floor_mod(min, MINS_PER_HOUR);
312 day += floor_div(hour, HOURS_PER_DAY);
313 hour = floor_mod(hour, HOURS_PER_DAY);
[a35b458]314
[c2b0e10]315 /* Adjust month. */
[1ab8539]316 year += floor_div(mon, 12);
317 mon = floor_mod(mon, 12);
[a35b458]318
[c2b0e10]319 /* Now the difficult part - days of month. */
[a35b458]320
[c2b0e10]321 /* First, deal with whole cycles of 400 years = 146097 days. */
[1ab8539]322 year += floor_div(day, 146097) * 400;
323 day = floor_mod(day, 146097);
[a35b458]324
[c2b0e10]325 /* Then, go in one year steps. */
326 if (mon <= 1) {
327 /* January and February. */
328 while (day > 365) {
[1ab8539]329 day -= is_leap_year(year) ? 366 : 365;
[c2b0e10]330 year++;
331 }
332 } else {
333 /* Rest of the year. */
334 while (day > 365) {
[1ab8539]335 day -= is_leap_year(year + 1) ? 366 : 365;
[c2b0e10]336 year++;
337 }
338 }
[a35b458]339
[c2b0e10]340 /* Finally, finish it off month per month. */
[1ab8539]341 while (day >= days_in_month(year, mon)) {
342 day -= days_in_month(year, mon);
[c2b0e10]343 mon++;
[a35b458]344
[c2b0e10]345 if (mon >= 12) {
346 mon -= 12;
347 year++;
348 }
349 }
[a35b458]350
[c2b0e10]351 /* Calculate the remaining two fields. */
[1ab8539]352 tm->tm_yday = day_of_year(year, mon, day + 1);
353 tm->tm_wday = day_of_week(year, mon, day + 1);
[a35b458]354
[c2b0e10]355 /* And put the values back to the struct. */
[bd41ac52]356 tm->tm_nsec = (int) nsec;
[c2b0e10]357 tm->tm_sec = (int) sec;
358 tm->tm_min = (int) min;
359 tm->tm_hour = (int) hour;
360 tm->tm_mday = (int) day + 1;
361 tm->tm_mon = (int) mon;
[a35b458]362
[1ab8539]363 /* Casts to work around POSIX brain-damage. */
364 if (year > ((int) INT_MAX) || year < ((int) INT_MIN)) {
365 tm->tm_year = (year < 0) ? ((int) INT_MIN) : ((int) INT_MAX);
[c2b0e10]366 return -1;
367 }
[a35b458]368
[c2b0e10]369 tm->tm_year = (int) year;
370 return 0;
371}
372
[7f9d97f3]373static int normalize_tm_time(struct tm *tm, time_t time)
374{
[bd41ac52]375 struct timespec ts = {
[7f9d97f3]376 .tv_sec = time,
[bd41ac52]377 .tv_nsec = 0
[7f9d97f3]378 };
379
[bd41ac52]380 return normalize_tm_ts(tm, &ts);
[7f9d97f3]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.