source: mainline/uspace/lib/posix/time.c@ 0a0e6e7

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 0a0e6e7 was d3e3a71, checked in by Maurizio Lombardi <m.lombardi85@…>, 13 years ago

libc: move difftime() from libposix to libc

  • Property mode set to 100644
File size: 13.3 KB
RevLine 
[2fc5072]1/*
2 * Copyright (c) 2011 Petr Koupy
3 * Copyright (c) 2011 Jiri Zarevucky
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * - Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * - Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * - The name of the author may not be used to endorse or promote products
16 * derived from this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30/** @addtogroup libposix
31 * @{
32 */
[4cf8ca6]33/** @file Time measurement support.
[2fc5072]34 */
35
[4d10fc8]36#define LIBPOSIX_INTERNAL
[2fc5072]37
[324d46b]38/* Must be first. */
39#include "stdbool.h"
40
[9b1503e]41#include "internal/common.h"
[4d10fc8]42#include "time.h"
[a6d908c1]43
[324d46b]44#include "ctype.h"
45#include "errno.h"
[3f466c33]46#include "signal.h"
[324d46b]47
[06cb827]48#include "libc/malloc.h"
[a6d908c1]49#include "libc/task.h"
50#include "libc/stats.h"
[3f466c33]51#include "libc/sys/time.h"
[2fc5072]52
[324d46b]53// TODO: test everything in this file
54
[e6165be]55/* In some places in this file, phrase "normalized broken-down time" is used.
56 * This means time broken down to components (year, month, day, hour, min, sec),
57 * in which every component is in its proper bounds. Non-normalized time could
58 * e.g. be 2011-54-5 29:13:-5, which would semantically mean start of year 2011
59 * + 53 months + 4 days + 29 hours + 13 minutes - 5 seconds.
60 */
61
62
63
[324d46b]64/* Helper functions ***********************************************************/
65
66#define HOURS_PER_DAY (24)
67#define MINS_PER_HOUR (60)
68#define SECS_PER_MIN (60)
69#define MINS_PER_DAY (MINS_PER_HOUR * HOURS_PER_DAY)
70#define SECS_PER_HOUR (SECS_PER_MIN * MINS_PER_HOUR)
71#define SECS_PER_DAY (SECS_PER_HOUR * HOURS_PER_DAY)
72
[55b1efd]73/**
74 * Checks whether the year is a leap year.
[4cf8ca6]75 *
[e6165be]76 * @param year Year since 1900 (e.g. for 1970, the value is 70).
77 * @return true if year is a leap year, false otherwise
[4cf8ca6]78 */
[324d46b]79static bool _is_leap_year(time_t year)
80{
81 year += 1900;
82
83 if (year % 400 == 0)
84 return true;
85 if (year % 100 == 0)
86 return false;
87 if (year % 4 == 0)
88 return true;
89 return false;
90}
91
[55b1efd]92/**
93 * Returns how many days there are in the given month of the given year.
94 * Note that year is only taken into account if month is February.
[4cf8ca6]95 *
[e6165be]96 * @param year Year since 1900 (can be negative).
97 * @param mon Month of the year. 0 for January, 11 for December.
98 * @return Number of days in the specified month.
[4cf8ca6]99 */
[324d46b]100static int _days_in_month(time_t year, time_t mon)
101{
102 assert(mon >= 0 && mon <= 11);
103
104 static int month_days[] =
105 { 31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
106
107 if (mon == 1) {
[e6165be]108 year += 1900;
[324d46b]109 /* february */
110 return _is_leap_year(year) ? 29 : 28;
111 } else {
112 return month_days[mon];
113 }
114}
115
[55b1efd]116/**
117 * For specified year, month and day of month, returns which day of that year
118 * it is.
[4cf8ca6]119 *
[e6165be]120 * For example, given date 2011-01-03, the corresponding expression is:
121 * _day_of_year(111, 0, 3) == 2
122 *
123 * @param year Year (year 1900 = 0, can be negative).
124 * @param mon Month (January = 0).
125 * @param mday Day of month (First day is 1).
126 * @return Day of year (First day is 0).
[4cf8ca6]127 */
[324d46b]128static int _day_of_year(time_t year, time_t mon, time_t mday)
129{
130 static int mdays[] =
131 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
132 static int leap_mdays[] =
133 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 };
134
135 return (_is_leap_year(year) ? leap_mdays[mon] : mdays[mon]) + mday - 1;
136}
137
[55b1efd]138/**
139 * Integer division that rounds to negative infinity.
140 * Used by some functions in this file.
[4cf8ca6]141 *
[86e81a9]142 * @param op1 Dividend.
[55b1efd]143 * @param op2 Divisor.
144 * @return Rounded quotient.
[324d46b]145 */
146static time_t _floor_div(time_t op1, time_t op2)
147{
148 if (op1 >= 0 || op1 % op2 == 0) {
149 return op1 / op2;
150 } else {
151 return op1 / op2 - 1;
152 }
153}
154
[55b1efd]155/**
156 * Modulo that rounds to negative infinity.
157 * Used by some functions in this file.
[4cf8ca6]158 *
[86e81a9]159 * @param op1 Dividend.
[55b1efd]160 * @param op2 Divisor.
161 * @return Remainder.
[324d46b]162 */
163static time_t _floor_mod(time_t op1, time_t op2)
164{
165 int div = _floor_div(op1, op2);
166
167 /* (a / b) * b + a % b == a */
168 /* thus, a % b == a - (a / b) * b */
169
170 int result = op1 - div * op2;
171
172 /* Some paranoid checking to ensure I didn't make a mistake here. */
173 assert(result >= 0);
174 assert(result < op2);
175 assert(div * op2 + result == op1);
176
177 return result;
178}
179
[55b1efd]180/**
181 * Number of days since the Epoch.
182 * Epoch is 1970-01-01, which is also equal to day 0.
[4cf8ca6]183 *
[e6165be]184 * @param year Year (year 1900 = 0, may be negative).
185 * @param mon Month (January = 0).
186 * @param mday Day of month (first day = 1).
187 * @return Number of days since the Epoch.
[4cf8ca6]188 */
[324d46b]189static time_t _days_since_epoch(time_t year, time_t mon, time_t mday)
190{
191 return (year - 70) * 365 + _floor_div(year - 69, 4) -
192 _floor_div(year - 1, 100) + _floor_div(year + 299, 400) +
193 _day_of_year(year, mon, mday);
194}
195
[55b1efd]196/**
197 * Which day of week the specified date is.
[4cf8ca6]198 *
[e6165be]199 * @param year Year (year 1900 = 0).
200 * @param mon Month (January = 0).
201 * @param mday Day of month (first = 1).
202 * @return Day of week (Sunday = 0).
[4cf8ca6]203 */
[324d46b]204static int _day_of_week(time_t year, time_t mon, time_t mday)
205{
206 /* 1970-01-01 is Thursday */
[e6165be]207 return _floor_mod((_days_since_epoch(year, mon, mday) + 4), 7);
[324d46b]208}
209
[55b1efd]210/**
211 * Normalizes the broken-down time and optionally adds specified amount of
212 * seconds.
[4cf8ca6]213 *
[e6165be]214 * @param tm Broken-down time to normalize.
215 * @param sec_add Seconds to add.
216 * @return 0 on success, -1 on overflow
[4cf8ca6]217 */
[f8b6d34c]218static int _normalize_time(struct tm *tm, time_t sec_add)
[324d46b]219{
220 // TODO: DST correction
221
[e6165be]222 /* Set initial values. */
223 time_t sec = tm->tm_sec + sec_add;
224 time_t min = tm->tm_min;
225 time_t hour = tm->tm_hour;
226 time_t day = tm->tm_mday - 1;
227 time_t mon = tm->tm_mon;
228 time_t year = tm->tm_year;
229
[324d46b]230 /* Adjust time. */
[e6165be]231 min += _floor_div(sec, SECS_PER_MIN);
232 sec = _floor_mod(sec, SECS_PER_MIN);
233 hour += _floor_div(min, MINS_PER_HOUR);
234 min = _floor_mod(min, MINS_PER_HOUR);
235 day += _floor_div(hour, HOURS_PER_DAY);
236 hour = _floor_mod(hour, HOURS_PER_DAY);
[324d46b]237
238 /* Adjust month. */
[e6165be]239 year += _floor_div(mon, 12);
240 mon = _floor_mod(mon, 12);
[324d46b]241
242 /* Now the difficult part - days of month. */
[e6165be]243
244 /* First, deal with whole cycles of 400 years = 146097 days. */
245 year += _floor_div(day, 146097) * 400;
246 day = _floor_mod(day, 146097);
247
248 /* Then, go in one year steps. */
249 if (mon <= 1) {
250 /* January and February. */
251 while (day > 365) {
252 day -= _is_leap_year(year) ? 366 : 365;
253 year++;
254 }
255 } else {
256 /* Rest of the year. */
257 while (day > 365) {
258 day -= _is_leap_year(year + 1) ? 366 : 365;
259 year++;
[324d46b]260 }
261 }
[e6165be]262
263 /* Finally, finish it off month per month. */
264 while (day >= _days_in_month(year, mon)) {
265 day -= _days_in_month(year, mon);
266 mon++;
267 if (mon >= 12) {
268 mon -= 12;
269 year++;
[324d46b]270 }
271 }
[e6165be]272
[324d46b]273 /* Calculate the remaining two fields. */
[e6165be]274 tm->tm_yday = _day_of_year(year, mon, day + 1);
275 tm->tm_wday = _day_of_week(year, mon, day + 1);
276
277 /* And put the values back to the struct. */
278 tm->tm_sec = (int) sec;
279 tm->tm_min = (int) min;
280 tm->tm_hour = (int) hour;
281 tm->tm_mday = (int) day + 1;
282 tm->tm_mon = (int) mon;
283
284 /* Casts to work around libc brain-damage. */
285 if (year > ((int)INT_MAX) || year < ((int)INT_MIN)) {
286 tm->tm_year = (year < 0) ? ((int)INT_MIN) : ((int)INT_MAX);
287 return -1;
288 }
289
290 tm->tm_year = (int) year;
291 return 0;
[324d46b]292}
293
294/******************************************************************************/
295
296int posix_daylight;
297long posix_timezone;
298char *posix_tzname[2];
299
[55b1efd]300/**
301 * Set timezone conversion information.
[4cf8ca6]302 */
[324d46b]303void posix_tzset(void)
304{
305 // TODO: read environment
306 posix_tzname[0] = (char *) "GMT";
307 posix_tzname[1] = (char *) "GMT";
308 posix_daylight = 0;
309 posix_timezone = 0;
310}
311
[55b1efd]312/**
313 * Converts a time value to a broken-down UTC time.
[4cf8ca6]314 *
[e6165be]315 * @param timer Time to convert.
316 * @param result Structure to store the result to.
317 * @return Value of result on success, NULL on overflow.
[4cf8ca6]318 */
[f8b6d34c]319struct tm *posix_gmtime_r(const time_t *restrict timer,
320 struct tm *restrict result)
[324d46b]321{
322 assert(timer != NULL);
323 assert(result != NULL);
324
[e6165be]325 /* Set result to epoch. */
326 result->tm_sec = 0;
327 result->tm_min = 0;
328 result->tm_hour = 0;
329 result->tm_mday = 1;
330 result->tm_mon = 0;
331 result->tm_year = 70; /* 1970 */
[324d46b]332
[e6165be]333 if (_normalize_time(result, *timer) == -1) {
[324d46b]334 errno = EOVERFLOW;
335 return NULL;
336 }
337
338 return result;
[2fc5072]339}
340
[55b1efd]341/**
342 * Converts a time value to a broken-down local time.
[4cf8ca6]343 *
[e6165be]344 * @param timer Time to convert.
345 * @param result Structure to store the result to.
346 * @return Value of result on success, NULL on overflow.
[4cf8ca6]347 */
[f8b6d34c]348struct tm *posix_localtime_r(const time_t *restrict timer,
349 struct tm *restrict result)
[3f466c33]350{
351 // TODO: deal with timezone
352 // currently assumes system and all times are in GMT
353 return posix_gmtime_r(timer, result);
354}
355
[55b1efd]356/**
357 * Converts broken-down time to a string in format
358 * "Sun Jan 1 00:00:00 1970\n". (Obsolete)
[e6165be]359 *
360 * @param timeptr Broken-down time structure.
361 * @param buf Buffer to store string to, must be at least ASCTIME_BUF_LEN
362 * bytes long.
363 * @return Value of buf.
[4cf8ca6]364 */
[f8b6d34c]365char *posix_asctime_r(const struct tm *restrict timeptr,
[324d46b]366 char *restrict buf)
367{
368 assert(timeptr != NULL);
369 assert(buf != NULL);
370
371 static const char *wday[] = {
372 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
373 };
374 static const char *mon[] = {
375 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
376 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
377 };
378
379 snprintf(buf, ASCTIME_BUF_LEN, "%s %s %2d %02d:%02d:%02d %d\n",
380 wday[timeptr->tm_wday],
381 mon[timeptr->tm_mon],
382 timeptr->tm_mday, timeptr->tm_hour,
383 timeptr->tm_min, timeptr->tm_sec,
384 1900 + timeptr->tm_year);
385
386 return buf;
[2fc5072]387}
388
[55b1efd]389/**
390 * Reentrant variant of ctime().
[4cf8ca6]391 *
[e6165be]392 * @param timer Time to convert.
393 * @param buf Buffer to store string to. Must be at least ASCTIME_BUF_LEN
394 * bytes long.
395 * @return Pointer to buf on success, NULL on falure.
[4cf8ca6]396 */
[3f466c33]397char *posix_ctime_r(const time_t *timer, char *buf)
398{
[f8b6d34c]399 struct tm loctime;
[3f466c33]400 if (posix_localtime_r(timer, &loctime) == NULL) {
401 return NULL;
402 }
403 return posix_asctime_r(&loctime, buf);
[2fc5072]404}
405
[55b1efd]406/**
407 * Get clock resolution. Only CLOCK_REALTIME is supported.
[4cf8ca6]408 *
[e6165be]409 * @param clock_id Clock ID.
410 * @param res Pointer to the variable where the resolution is to be written.
411 * @return 0 on success, -1 with errno set on failure.
[4cf8ca6]412 */
[3f466c33]413int posix_clock_getres(posix_clockid_t clock_id, struct posix_timespec *res)
414{
415 assert(res != NULL);
416
417 switch (clock_id) {
418 case CLOCK_REALTIME:
419 res->tv_sec = 0;
420 res->tv_nsec = 1000; /* Microsecond resolution. */
421 return 0;
422 default:
423 errno = EINVAL;
424 return -1;
425 }
426}
427
[55b1efd]428/**
429 * Get time. Only CLOCK_REALTIME is supported.
[4cf8ca6]430 *
[e6165be]431 * @param clock_id ID of the clock to query.
432 * @param tp Pointer to the variable where the time is to be written.
[55b1efd]433 * @return 0 on success, -1 with errno on failure.
[4cf8ca6]434 */
[3f466c33]435int posix_clock_gettime(posix_clockid_t clock_id, struct posix_timespec *tp)
436{
437 assert(tp != NULL);
438
439 switch (clock_id) {
440 case CLOCK_REALTIME:
441 ;
442 struct timeval tv;
443 gettimeofday(&tv, NULL);
444 tp->tv_sec = tv.tv_sec;
445 tp->tv_nsec = tv.tv_usec * 1000;
446 return 0;
447 default:
448 errno = EINVAL;
449 return -1;
450 }
451}
452
[55b1efd]453/**
454 * Set time on a specified clock. As HelenOS doesn't support this yet,
455 * this function always fails.
[4cf8ca6]456 *
[e6165be]457 * @param clock_id ID of the clock to set.
458 * @param tp Time to set.
459 * @return 0 on success, -1 with errno on failure.
[4cf8ca6]460 */
[3f466c33]461int posix_clock_settime(posix_clockid_t clock_id,
462 const struct posix_timespec *tp)
463{
464 assert(tp != NULL);
465
466 switch (clock_id) {
467 case CLOCK_REALTIME:
468 // TODO: setting clock
469 // FIXME: HelenOS doesn't actually support hardware
470 // clock yet
471 errno = EPERM;
472 return -1;
473 default:
474 errno = EINVAL;
475 return -1;
476 }
477}
478
[55b1efd]479/**
480 * Sleep on a specified clock.
[4cf8ca6]481 *
[e6165be]482 * @param clock_id ID of the clock to sleep on (only CLOCK_REALTIME supported).
483 * @param flags Flags (none supported).
484 * @param rqtp Sleep time.
485 * @param rmtp Remaining time is written here if sleep is interrupted.
486 * @return 0 on success, -1 with errno set on failure.
[4cf8ca6]487 */
[3f466c33]488int posix_clock_nanosleep(posix_clockid_t clock_id, int flags,
489 const struct posix_timespec *rqtp, struct posix_timespec *rmtp)
490{
491 assert(rqtp != NULL);
492 assert(rmtp != NULL);
493
494 switch (clock_id) {
495 case CLOCK_REALTIME:
496 // TODO: interruptible sleep
497 if (rqtp->tv_sec != 0) {
498 sleep(rqtp->tv_sec);
499 }
500 if (rqtp->tv_nsec != 0) {
501 usleep(rqtp->tv_nsec / 1000);
502 }
503 return 0;
504 default:
505 errno = EINVAL;
506 return -1;
507 }
508}
509
[55b1efd]510/**
511 * Get CPU time used since the process invocation.
[06cb827]512 *
513 * @return Consumed CPU cycles by this process or -1 if not available.
[823a929]514 */
515posix_clock_t posix_clock(void)
516{
[06cb827]517 posix_clock_t total_cycles = -1;
518 stats_task_t *task_stats = stats_get_task(task_get_id());
519 if (task_stats) {
[cb948777]520 total_cycles = (posix_clock_t) (task_stats->kcycles +
521 task_stats->ucycles);
[a12f7f1]522 free(task_stats);
523 task_stats = 0;
[06cb827]524 }
525
526 return total_cycles;
[823a929]527}
528
[2fc5072]529/** @}
530 */
Note: See TracBrowser for help on using the repository browser.