source: mainline/uspace/lib/c/generic/time.c@ 1938b381

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 1938b381 was 09ab0a9a, checked in by Jiri Svoboda <jiri@…>, 7 years ago

Fix vertical spacing with new Ccheck revision.

  • 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
[58e7b26]54#define ASCTIME_BUF_LEN 27
[1ab8539]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
[1ab8539]382/** Which day the week-based year starts on.
383 *
384 * Relative to the first calendar day. E.g. if the year starts
385 * on December 31st, the return value is -1.
[c2b0e10]386 *
387 * @param Year since 1900.
[1ab8539]388 *
[c2b0e10]389 * @return Offset of week-based year relative to calendar year.
[1ab8539]390 *
[c2b0e10]391 */
[1ab8539]392static int wbyear_offset(int year)
[c2b0e10]393{
[1ab8539]394 int start_wday = day_of_week(year, 0, 1);
[a35b458]395
[1ab8539]396 return floor_mod(4 - start_wday, 7) - 3;
[c2b0e10]397}
398
[1ab8539]399/** Week-based year of the specified time.
[c2b0e10]400 *
401 * @param tm Normalized broken-down time.
[1ab8539]402 *
[c2b0e10]403 * @return Week-based year.
[1ab8539]404 *
[c2b0e10]405 */
[1ab8539]406static int wbyear(const struct tm *tm)
[c2b0e10]407{
[1ab8539]408 int day = tm->tm_yday - wbyear_offset(tm->tm_year);
[a35b458]409
[c2b0e10]410 if (day < 0) {
411 /* Last week of previous year. */
412 return tm->tm_year - 1;
413 }
[a35b458]414
[1ab8539]415 if (day > 364 + is_leap_year(tm->tm_year)) {
[c2b0e10]416 /* First week of next year. */
417 return tm->tm_year + 1;
418 }
[a35b458]419
[c2b0e10]420 /* All the other days are in the calendar year. */
421 return tm->tm_year;
422}
423
[1ab8539]424/** Week number of the year (assuming weeks start on Sunday).
425 *
[c2b0e10]426 * The first Sunday of January is the first day of week 1;
427 * days in the new year before this are in week 0.
428 *
429 * @param tm Normalized broken-down time.
[1ab8539]430 *
[c2b0e10]431 * @return The week number (0 - 53).
[1ab8539]432 *
[c2b0e10]433 */
[1ab8539]434static int sun_week_number(const struct tm *tm)
[c2b0e10]435{
[1ab8539]436 int first_day = (7 - day_of_week(tm->tm_year, 0, 1)) % 7;
[a35b458]437
[c2b0e10]438 return (tm->tm_yday - first_day + 7) / 7;
439}
440
[1ab8539]441/** Week number of the year (assuming weeks start on Monday).
442 *
443 * If the week containing January 1st has four or more days
444 * in the new year, then it is considered week 1. Otherwise,
445 * it is the last week of the previous year, and the next week
446 * is week 1. Both January 4th and the first Thursday
[c2b0e10]447 * of January are always in week 1.
448 *
449 * @param tm Normalized broken-down time.
[1ab8539]450 *
[c2b0e10]451 * @return The week number (1 - 53).
[1ab8539]452 *
[c2b0e10]453 */
[1ab8539]454static int iso_week_number(const struct tm *tm)
[c2b0e10]455{
[1ab8539]456 int day = tm->tm_yday - wbyear_offset(tm->tm_year);
[a35b458]457
[c2b0e10]458 if (day < 0) {
459 /* Last week of previous year. */
460 return 53;
461 }
[a35b458]462
[1ab8539]463 if (day > 364 + is_leap_year(tm->tm_year)) {
[c2b0e10]464 /* First week of next year. */
465 return 1;
466 }
[a35b458]467
[c2b0e10]468 /* All the other days give correct answer. */
469 return (day / 7 + 1);
470}
471
[1ab8539]472/** Week number of the year (assuming weeks start on Monday).
473 *
[c2b0e10]474 * The first Monday of January is the first day of week 1;
[1ab8539]475 * days in the new year before this are in week 0.
[c2b0e10]476 *
477 * @param tm Normalized broken-down time.
[1ab8539]478 *
[c2b0e10]479 * @return The week number (0 - 53).
[1ab8539]480 *
[c2b0e10]481 */
[1ab8539]482static int mon_week_number(const struct tm *tm)
[c2b0e10]483{
[1ab8539]484 int first_day = (1 - day_of_week(tm->tm_year, 0, 1)) % 7;
[a35b458]485
[c2b0e10]486 return (tm->tm_yday - first_day + 7) / 7;
487}
488
[bd41ac52]489static void ts_normalize(struct timespec *ts)
[7f9d97f3]490{
[bd41ac52]491 while (ts->tv_nsec >= NSECS_PER_SEC) {
492 ts->tv_sec++;
493 ts->tv_nsec -= NSECS_PER_SEC;
[7f9d97f3]494 }
[bd41ac52]495 while (ts->tv_nsec < 0) {
496 ts->tv_sec--;
497 ts->tv_nsec += NSECS_PER_SEC;
[7f9d97f3]498 }
499}
500
[bd41ac52]501/** Add nanoseconds to given timespec.
[daa90e8]502 *
[bd41ac52]503 * @param ts Destination timespec.
504 * @param nsecs Number of nanoseconds to add.
[2c577e0b]505 *
[daa90e8]506 */
[bd41ac52]507void ts_add_diff(struct timespec *ts, nsec_t nsecs)
[daa90e8]508{
[bd41ac52]509 ts->tv_sec += nsecs / NSECS_PER_SEC;
510 ts->tv_nsec += nsecs % NSECS_PER_SEC;
511 ts_normalize(ts);
[7f9d97f3]512}
513
[bd41ac52]514/** Add two timespecs.
[7f9d97f3]515 *
[bd41ac52]516 * @param ts1 First timespec.
517 * @param ts2 Second timespec.
[7f9d97f3]518 */
[bd41ac52]519void ts_add(struct timespec *ts1, const struct timespec *ts2)
[7f9d97f3]520{
[bd41ac52]521 ts1->tv_sec += ts2->tv_sec;
522 ts1->tv_nsec += ts2->tv_nsec;
523 ts_normalize(ts1);
[daa90e8]524}
525
[bd41ac52]526/** Subtract two timespecs.
[daa90e8]527 *
[bd41ac52]528 * @param ts1 First timespec.
529 * @param ts2 Second timespec.
[2c577e0b]530 *
[bd41ac52]531 * @return Difference between ts1 and ts2 (ts1 - ts2) in nanoseconds.
[daa90e8]532 *
533 */
[bd41ac52]534nsec_t ts_sub_diff(const struct timespec *ts1, const struct timespec *ts2)
[daa90e8]535{
[bd41ac52]536 return (nsec_t) (ts1->tv_nsec - ts2->tv_nsec) +
537 SEC2NSEC((ts1->tv_sec - ts2->tv_sec));
[7f9d97f3]538}
539
[bd41ac52]540/** Subtract two timespecs.
[7f9d97f3]541 *
[bd41ac52]542 * @param ts1 First timespec.
543 * @param ts2 Second timespec.
[7f9d97f3]544 *
545 */
[bd41ac52]546void ts_sub(struct timespec *ts1, const struct timespec *ts2)
[7f9d97f3]547{
[bd41ac52]548 ts1->tv_sec -= ts2->tv_sec;
549 ts1->tv_nsec -= ts2->tv_nsec;
550 ts_normalize(ts1);
[daa90e8]551}
552
[bd41ac52]553/** Decide if one timespec is greater than the other.
[daa90e8]554 *
[bd41ac52]555 * @param ts1 First timespec.
556 * @param ts2 Second timespec.
[2c577e0b]557 *
[bd41ac52]558 * @return True if ts1 is greater than ts2.
559 * @return False otherwise.
[daa90e8]560 *
561 */
[bd41ac52]562bool ts_gt(const struct timespec *ts1, const struct timespec *ts2)
[daa90e8]563{
[bd41ac52]564 if (ts1->tv_sec > ts2->tv_sec)
[2c577e0b]565 return true;
[a35b458]566
[bd41ac52]567 if ((ts1->tv_sec == ts2->tv_sec) && (ts1->tv_nsec > ts2->tv_nsec))
[2c577e0b]568 return true;
[a35b458]569
[2c577e0b]570 return false;
[daa90e8]571}
572
[bd41ac52]573/** Decide if one timespec is greater than or equal to the other.
[daa90e8]574 *
[bd41ac52]575 * @param ts1 First timespec.
576 * @param ts2 Second timespec.
[2c577e0b]577 *
[bd41ac52]578 * @return True if ts1 is greater than or equal to ts2.
579 * @return False otherwise.
[daa90e8]580 *
581 */
[bd41ac52]582bool ts_gteq(const struct timespec *ts1, const struct timespec *ts2)
[daa90e8]583{
[bd41ac52]584 if (ts1->tv_sec > ts2->tv_sec)
[2c577e0b]585 return true;
[a35b458]586
[bd41ac52]587 if ((ts1->tv_sec == ts2->tv_sec) && (ts1->tv_nsec >= ts2->tv_nsec))
[2c577e0b]588 return true;
[a35b458]589
[2c577e0b]590 return false;
[daa90e8]591}
592
[bd41ac52]593/** Get real time from a RTC service.
[2c577e0b]594 *
[bd41ac52]595 * @param[out] ts Timespec to hold time read from the RTC service (if
596 * available). If no such service exists, the returned time
597 * corresponds to system uptime.
[0b99e40]598 */
[bd41ac52]599void getrealtime(struct timespec *ts)
[3a58347]600{
601 if (clock_conn == NULL) {
[1ab8539]602 category_id_t cat_id;
[b7fd2a0]603 errno_t rc = loc_category_get_id("clock", &cat_id, IPC_FLAG_BLOCKING);
[3a58347]604 if (rc != EOK)
[1ab8539]605 goto fallback;
[a35b458]606
[1ab8539]607 service_id_t *svc_ids;
608 size_t svc_cnt;
[3a58347]609 rc = loc_category_get_svcs(cat_id, &svc_ids, &svc_cnt);
610 if (rc != EOK)
[1ab8539]611 goto fallback;
[a35b458]612
[3a58347]613 if (svc_cnt == 0)
[1ab8539]614 goto fallback;
[a35b458]615
[1ab8539]616 char *svc_name;
[3a58347]617 rc = loc_service_get_name(svc_ids[0], &svc_name);
[1ab8539]618 free(svc_ids);
[3a58347]619 if (rc != EOK)
[1ab8539]620 goto fallback;
[a35b458]621
[1ab8539]622 service_id_t svc_id;
[3a58347]623 rc = loc_service_get_id(svc_name, &svc_id, 0);
[1ab8539]624 free(svc_name);
[3a58347]625 if (rc != EOK)
[1ab8539]626 goto fallback;
[a35b458]627
[f9b2cb4c]628 clock_conn = loc_service_connect(svc_id, INTERFACE_DDF,
629 IPC_FLAG_BLOCKING);
[3a58347]630 if (!clock_conn)
[1ab8539]631 goto fallback;
[3a58347]632 }
[a35b458]633
[1ab8539]634 struct tm time;
[b7fd2a0]635 errno_t rc = clock_dev_time_get(clock_conn, &time);
[3a58347]636 if (rc != EOK)
[1ab8539]637 goto fallback;
[a35b458]638
[bd41ac52]639 ts->tv_nsec = time.tm_nsec;
640 ts->tv_sec = mktime(&time);
[a35b458]641
[1ab8539]642 return;
[a35b458]643
[1ab8539]644fallback:
[bd41ac52]645 getuptime(ts);
[3a58347]646}
647
[bd41ac52]648/** Get system uptime.
649 *
650 * @param[out] ts Timespec to hold time current uptime.
651 *
652 * The time variables are memory mapped (read-only) from kernel which
653 * updates them periodically.
654 *
655 * As it is impossible to read 2 values atomically, we use a trick:
656 * First we read the seconds, then we read the microseconds, then we
657 * read the seconds again. If a second elapsed in the meantime, set
658 * the microseconds to zero.
659 *
660 * This assures that the values returned by two subsequent calls
661 * to getuptime() are monotonous.
662 *
663 */
664void getuptime(struct timespec *ts)
[0b99e40]665{
[6119f24]666 if (ktime == NULL) {
667 uintptr_t faddr;
[b7fd2a0]668 errno_t rc = sysinfo_get_value("clock.faddr", &faddr);
[6119f24]669 if (rc != EOK) {
670 errno = rc;
[1ab8539]671 goto fallback;
[6119f24]672 }
[a35b458]673
[bf9cb2f]674 void *addr = AS_AREA_ANY;
[8442d10]675 rc = physmem_map(faddr, 1, AS_AREA_READ | AS_AREA_CACHEABLE,
676 &addr);
[6119f24]677 if (rc != EOK) {
678 as_area_destroy(addr);
679 errno = rc;
[1ab8539]680 goto fallback;
[6119f24]681 }
[a35b458]682
[6119f24]683 ktime = addr;
[0b99e40]684 }
[a35b458]685
[2c577e0b]686 sysarg_t s2 = ktime->seconds2;
[a35b458]687
[5bd03eb]688 read_barrier();
[bd41ac52]689 ts->tv_nsec = USEC2NSEC(ktime->useconds);
[a35b458]690
[0b99e40]691 read_barrier();
[2c577e0b]692 sysarg_t s1 = ktime->seconds1;
[a35b458]693
[2d1fde3b]694 if (s1 != s2) {
[bd41ac52]695 ts->tv_sec = max(s1, s2);
696 ts->tv_nsec = 0;
[2d1fde3b]697 } else
[bd41ac52]698 ts->tv_sec = s1;
[a35b458]699
[1ab8539]700 return;
[a35b458]701
[1ab8539]702fallback:
[bd41ac52]703 ts->tv_sec = 0;
704 ts->tv_nsec = 0;
[0b99e40]705}
[44c6d88d]706
[813a703]707time_t time(time_t *tloc)
708{
[bd41ac52]709 struct timespec ts;
710 getrealtime(&ts);
[a35b458]711
[813a703]712 if (tloc)
[bd41ac52]713 *tloc = ts.tv_sec;
[a35b458]714
[bd41ac52]715 return ts.tv_sec;
[813a703]716}
717
[bd41ac52]718void udelay(sysarg_t time)
[5fd3f2d]719{
720 (void) __SYSCALL1(SYS_THREAD_UDELAY, (sysarg_t) time);
721}
722
[1ab8539]723/** Get time from broken-down time.
724 *
725 * First normalize the provided broken-down time
726 * (moves all values to their proper bounds) and
727 * then try to calculate the appropriate time_t
728 * representation.
[c2b0e10]729 *
730 * @param tm Broken-down time.
[1ab8539]731 *
732 * @return time_t representation of the time.
733 * @return Undefined value on overflow.
734 *
[c2b0e10]735 */
736time_t mktime(struct tm *tm)
737{
738 // TODO: take DST flag into account
739 // TODO: detect overflow
[a35b458]740
[7f9d97f3]741 normalize_tm_time(tm, 0);
[1ab8539]742 return secs_since_epoch(tm);
[c2b0e10]743}
744
[1ab8539]745/*
746 * FIXME: This requires POSIX-correct snprintf.
747 * Otherwise it won't work with non-ASCII chars.
748 */
749#define APPEND(...) \
750 { \
751 consumed = snprintf(ptr, remaining, __VA_ARGS__); \
752 if (consumed >= remaining) \
753 return 0; \
754 \
755 ptr += consumed; \
756 remaining -= consumed; \
757 }
758
759#define RECURSE(fmt) \
760 { \
761 consumed = strftime(ptr, remaining, fmt, tm); \
762 if (consumed == 0) \
763 return 0; \
764 \
765 ptr += consumed; \
766 remaining -= consumed; \
767 }
768
769#define TO_12H(hour) \
770 (((hour) > 12) ? ((hour) - 12) : \
771 (((hour) == 0) ? 12 : (hour)))
772
773/** Convert time and date to a string.
774 *
775 * @param s Buffer to write string to.
[c2b0e10]776 * @param maxsize Size of the buffer.
[1ab8539]777 * @param format Format of the output.
778 * @param tm Broken-down time to format.
779 *
[c2b0e10]780 * @return Number of bytes written.
[1ab8539]781 *
[c2b0e10]782 */
783size_t strftime(char *restrict s, size_t maxsize,
784 const char *restrict format, const struct tm *restrict tm)
785{
786 assert(s != NULL);
787 assert(format != NULL);
788 assert(tm != NULL);
[a35b458]789
[c2b0e10]790 // TODO: use locale
[a35b458]791
[c2b0e10]792 static const char *wday_abbr[] = {
793 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
794 };
[a35b458]795
[c2b0e10]796 static const char *wday[] = {
797 "Sunday", "Monday", "Tuesday", "Wednesday",
798 "Thursday", "Friday", "Saturday"
799 };
[a35b458]800
[c2b0e10]801 static const char *mon_abbr[] = {
802 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
803 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
804 };
[a35b458]805
[c2b0e10]806 static const char *mon[] = {
807 "January", "February", "March", "April", "May", "June", "July",
808 "August", "September", "October", "November", "December"
809 };
[a35b458]810
[1ab8539]811 if (maxsize < 1)
[c2b0e10]812 return 0;
[a35b458]813
[c2b0e10]814 char *ptr = s;
815 size_t consumed;
816 size_t remaining = maxsize;
[a35b458]817
[c2b0e10]818 while (*format != '\0') {
819 if (*format != '%') {
[1ab8539]820 APPEND("%c", *format);
[c2b0e10]821 format++;
822 continue;
823 }
[a35b458]824
[c2b0e10]825 format++;
[1ab8539]826 if ((*format == '0') || (*format == '+')) {
[c2b0e10]827 // TODO: padding
828 format++;
829 }
[a35b458]830
[c2b0e10]831 while (isdigit(*format)) {
832 // TODO: padding
833 format++;
834 }
[a35b458]835
[1ab8539]836 if ((*format == 'O') || (*format == 'E')) {
[c2b0e10]837 // TODO: locale's alternative format
838 format++;
839 }
[a35b458]840
[c2b0e10]841 switch (*format) {
842 case 'a':
[1ab8539]843 APPEND("%s", wday_abbr[tm->tm_wday]);
844 break;
[c2b0e10]845 case 'A':
[1ab8539]846 APPEND("%s", wday[tm->tm_wday]);
847 break;
[c2b0e10]848 case 'b':
[1ab8539]849 APPEND("%s", mon_abbr[tm->tm_mon]);
850 break;
[c2b0e10]851 case 'B':
[1ab8539]852 APPEND("%s", mon[tm->tm_mon]);
853 break;
[c2b0e10]854 case 'c':
855 // TODO: locale-specific datetime format
[1ab8539]856 RECURSE("%Y-%m-%d %H:%M:%S");
857 break;
[c2b0e10]858 case 'C':
[1ab8539]859 APPEND("%02d", (1900 + tm->tm_year) / 100);
860 break;
[c2b0e10]861 case 'd':
[1ab8539]862 APPEND("%02d", tm->tm_mday);
863 break;
[c2b0e10]864 case 'D':
[1ab8539]865 RECURSE("%m/%d/%y");
866 break;
[c2b0e10]867 case 'e':
[1ab8539]868 APPEND("%2d", tm->tm_mday);
869 break;
[c2b0e10]870 case 'F':
[1ab8539]871 RECURSE("%+4Y-%m-%d");
872 break;
[c2b0e10]873 case 'g':
[1ab8539]874 APPEND("%02d", wbyear(tm) % 100);
875 break;
[c2b0e10]876 case 'G':
[1ab8539]877 APPEND("%d", wbyear(tm));
878 break;
[c2b0e10]879 case 'h':
[1ab8539]880 RECURSE("%b");
881 break;
[c2b0e10]882 case 'H':
[1ab8539]883 APPEND("%02d", tm->tm_hour);
884 break;
[c2b0e10]885 case 'I':
[1ab8539]886 APPEND("%02d", TO_12H(tm->tm_hour));
887 break;
[c2b0e10]888 case 'j':
[1ab8539]889 APPEND("%03d", tm->tm_yday);
890 break;
[c2b0e10]891 case 'k':
[1ab8539]892 APPEND("%2d", tm->tm_hour);
893 break;
[c2b0e10]894 case 'l':
[1ab8539]895 APPEND("%2d", TO_12H(tm->tm_hour));
896 break;
[c2b0e10]897 case 'm':
[1ab8539]898 APPEND("%02d", tm->tm_mon);
899 break;
[c2b0e10]900 case 'M':
[1ab8539]901 APPEND("%02d", tm->tm_min);
902 break;
[c2b0e10]903 case 'n':
[1ab8539]904 APPEND("\n");
905 break;
[c2b0e10]906 case 'p':
[1ab8539]907 APPEND("%s", tm->tm_hour < 12 ? "AM" : "PM");
908 break;
[c2b0e10]909 case 'P':
[1ab8539]910 APPEND("%s", tm->tm_hour < 12 ? "am" : "PM");
911 break;
[c2b0e10]912 case 'r':
[1ab8539]913 RECURSE("%I:%M:%S %p");
914 break;
[c2b0e10]915 case 'R':
[1ab8539]916 RECURSE("%H:%M");
917 break;
[c2b0e10]918 case 's':
[bd41ac52]919 APPEND("%lld", secs_since_epoch(tm));
[1ab8539]920 break;
[c2b0e10]921 case 'S':
[1ab8539]922 APPEND("%02d", tm->tm_sec);
923 break;
[c2b0e10]924 case 't':
[1ab8539]925 APPEND("\t");
926 break;
[c2b0e10]927 case 'T':
[1ab8539]928 RECURSE("%H:%M:%S");
929 break;
[c2b0e10]930 case 'u':
[1ab8539]931 APPEND("%d", (tm->tm_wday == 0) ? 7 : tm->tm_wday);
[c2b0e10]932 break;
933 case 'U':
[1ab8539]934 APPEND("%02d", sun_week_number(tm));
935 break;
[c2b0e10]936 case 'V':
[1ab8539]937 APPEND("%02d", iso_week_number(tm));
938 break;
[c2b0e10]939 case 'w':
[1ab8539]940 APPEND("%d", tm->tm_wday);
941 break;
[c2b0e10]942 case 'W':
[1ab8539]943 APPEND("%02d", mon_week_number(tm));
944 break;
[c2b0e10]945 case 'x':
946 // TODO: locale-specific date format
[1ab8539]947 RECURSE("%Y-%m-%d");
948 break;
[c2b0e10]949 case 'X':
950 // TODO: locale-specific time format
[1ab8539]951 RECURSE("%H:%M:%S");
952 break;
[c2b0e10]953 case 'y':
[1ab8539]954 APPEND("%02d", tm->tm_year % 100);
955 break;
[c2b0e10]956 case 'Y':
[1ab8539]957 APPEND("%d", 1900 + tm->tm_year);
958 break;
[c2b0e10]959 case 'z':
960 // TODO: timezone
961 break;
962 case 'Z':
963 // TODO: timezone
964 break;
965 case '%':
[1ab8539]966 APPEND("%%");
[c2b0e10]967 break;
968 default:
969 /* Invalid specifier, print verbatim. */
[1ab8539]970 while (*format != '%')
[c2b0e10]971 format--;
[a35b458]972
[1ab8539]973 APPEND("%%");
[c2b0e10]974 break;
975 }
[a35b458]976
[c2b0e10]977 format++;
978 }
[a35b458]979
[c2b0e10]980 return maxsize - remaining;
981}
982
[1ab8539]983/** Convert a time value to a broken-down UTC time/
[f7ea5400]984 *
[1ab8539]985 * @param time Time to convert
986 * @param result Structure to store the result to
987 *
[cde999a]988 * @return EOK or an error code
[f7ea5400]989 *
990 */
[b7fd2a0]991errno_t time_utc2tm(const time_t time, struct tm *restrict result)
[f7ea5400]992{
993 assert(result != NULL);
[a35b458]994
[5b3394c]995 /* Set result to epoch. */
[bd41ac52]996 result->tm_nsec = 0;
[f7ea5400]997 result->tm_sec = 0;
998 result->tm_min = 0;
999 result->tm_hour = 0;
1000 result->tm_mday = 1;
1001 result->tm_mon = 0;
1002 result->tm_year = 70; /* 1970 */
[a35b458]1003
[7f9d97f3]1004 if (normalize_tm_time(result, time) == -1)
[f7ea5400]1005 return EOVERFLOW;
[a35b458]1006
[f7ea5400]1007 return EOK;
[5b3394c]1008}
1009
[1ab8539]1010/** Convert a time value to a NULL-terminated string.
1011 *
1012 * The format is "Wed Jun 30 21:49:08 1993\n" expressed in UTC.
1013 *
1014 * @param time Time to convert.
1015 * @param buf Buffer to store the string to, must be at least
1016 * ASCTIME_BUF_LEN bytes long.
[f7ea5400]1017 *
[cde999a]1018 * @return EOK or an error code.
[f7ea5400]1019 *
1020 */
[b7fd2a0]1021errno_t time_utc2str(const time_t time, char *restrict buf)
[f7ea5400]1022{
[1ab8539]1023 struct tm tm;
[b7fd2a0]1024 errno_t ret = time_utc2tm(time, &tm);
[1ab8539]1025 if (ret != EOK)
1026 return ret;
[a35b458]1027
[1ab8539]1028 time_tm2str(&tm, buf);
[f7ea5400]1029 return EOK;
1030}
1031
[1ab8539]1032/** Convert broken-down time to a NULL-terminated string.
1033 *
1034 * The format is "Sun Jan 1 00:00:00 1970\n". (Obsolete)
[8219eb9]1035 *
1036 * @param timeptr Broken-down time structure.
[1ab8539]1037 * @param buf Buffer to store string to, must be at least
1038 * ASCTIME_BUF_LEN bytes long.
1039 *
[8219eb9]1040 */
[664fc031]1041void time_tm2str(const struct tm *restrict timeptr, char *restrict buf)
[8219eb9]1042{
1043 assert(timeptr != NULL);
[f7ea5400]1044 assert(buf != NULL);
[a35b458]1045
[8219eb9]1046 static const char *wday[] = {
1047 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
1048 };
[a35b458]1049
[8219eb9]1050 static const char *mon[] = {
1051 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1052 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1053 };
[a35b458]1054
[8219eb9]1055 snprintf(buf, ASCTIME_BUF_LEN, "%s %s %2d %02d:%02d:%02d %d\n",
1056 wday[timeptr->tm_wday],
1057 mon[timeptr->tm_mon],
1058 timeptr->tm_mday, timeptr->tm_hour,
1059 timeptr->tm_min, timeptr->tm_sec,
1060 1900 + timeptr->tm_year);
1061}
1062
[1ab8539]1063/** Converts a time value to a broken-down local time.
1064 *
1065 * Time is expressed relative to the user's specified timezone.
[f7ea5400]1066 *
[7f9d97f3]1067 * @param tv Timeval to convert.
[1ab8539]1068 * @param result Structure to store the result to.
1069 *
[cde999a]1070 * @return EOK on success or an error code.
[f6cb995]1071 *
1072 */
[bd41ac52]1073errno_t time_ts2tm(const struct timespec *ts, struct tm *restrict result)
[f6cb995]1074{
[1ab8539]1075 // TODO: Deal with timezones.
1076 // Currently assumes system and all times are in UTC
[a35b458]1077
[f6cb995]1078 /* Set result to epoch. */
[bd41ac52]1079 result->tm_nsec = 0;
[f7ea5400]1080 result->tm_sec = 0;
1081 result->tm_min = 0;
1082 result->tm_hour = 0;
1083 result->tm_mday = 1;
1084 result->tm_mon = 0;
1085 result->tm_year = 70; /* 1970 */
[a35b458]1086
[bd41ac52]1087 if (normalize_tm_ts(result, ts) == -1)
[f7ea5400]1088 return EOVERFLOW;
[a35b458]1089
[f7ea5400]1090 return EOK;
[f6cb995]1091}
[c2b0e10]1092
[7f9d97f3]1093/** Converts a time value to a broken-down local time.
1094 *
1095 * Time is expressed relative to the user's specified timezone.
1096 *
1097 * @param timer Time to convert.
1098 * @param result Structure to store the result to.
1099 *
[cde999a]1100 * @return EOK on success or an error code.
[7f9d97f3]1101 *
1102 */
[b7fd2a0]1103errno_t time_local2tm(const time_t time, struct tm *restrict result)
[7f9d97f3]1104{
[bd41ac52]1105 struct timespec ts = {
[7f9d97f3]1106 .tv_sec = time,
[bd41ac52]1107 .tv_nsec = 0
[7f9d97f3]1108 };
1109
[bd41ac52]1110 return time_ts2tm(&ts, result);
[7f9d97f3]1111}
1112
[1ab8539]1113/** Convert the calendar time to a NULL-terminated string.
1114 *
1115 * The format is "Wed Jun 30 21:49:08 1993\n" expressed relative to the
[f7ea5400]1116 * user's specified timezone.
1117 *
[1ab8539]1118 * @param timer Time to convert.
1119 * @param buf Buffer to store the string to. Must be at least
1120 * ASCTIME_BUF_LEN bytes long.
1121 *
[cde999a]1122 * @return EOK on success or an error code.
[1ab8539]1123 *
[56b308e]1124 */
[b7fd2a0]1125errno_t time_local2str(const time_t time, char *buf)
[56b308e]1126{
[f7ea5400]1127 struct tm loctime;
[b7fd2a0]1128 errno_t ret = time_local2tm(time, &loctime);
[1ab8539]1129 if (ret != EOK)
1130 return ret;
[a35b458]1131
[664fc031]1132 time_tm2str(&loctime, buf);
[f7ea5400]1133 return EOK;
[56b308e]1134}
1135
[1ab8539]1136/** Calculate the difference between two times, in seconds.
1137 *
[d3e3a71]1138 * @param time1 First time.
1139 * @param time0 Second time.
[1ab8539]1140 *
1141 * @return Time difference in seconds.
1142 *
[d3e3a71]1143 */
1144double difftime(time_t time1, time_t time0)
1145{
1146 return (double) (time1 - time0);
1147}
1148
[a46da63]1149/** @}
[b2951e2]1150 */
Note: See TracBrowser for help on using the repository browser.