source: mainline/uspace/lib/posix/time.c@ 41b764b7

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

Merge mainline changes

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