|
| 1 | +/* |
| 2 | + * Copyright (c) 2024, Tenstorrent AI ULC |
| 3 | + * |
| 4 | + * SPDX-License-Identifier: Apache-2.0 |
| 5 | + */ |
| 6 | + |
| 7 | +#include "../options/posix_clock.h" |
| 8 | +#include <string.h> |
| 9 | + |
| 10 | +#include <zephyr/posix/sys/timerfd.h> |
| 11 | +#include <zephyr/zvfs/timerfd.h> |
| 12 | + |
| 13 | +int timerfd_create(int clockid, int flags) |
| 14 | +{ |
| 15 | + return zvfs_timerfd(clockid, flags); |
| 16 | +}; |
| 17 | + |
| 18 | +int timerfd_gettime(int fd, struct itimerspec *curr_value) |
| 19 | +{ |
| 20 | + int ret; |
| 21 | + uint32_t value, period; |
| 22 | + int32_t leftover; |
| 23 | + int64_t nsecs, secs; |
| 24 | + |
| 25 | + ret = zvfs_timerfd_gettime(fd, &value, &period); |
| 26 | + if (ret != 0) { |
| 27 | + return ret; |
| 28 | + } |
| 29 | + |
| 30 | + /* converts value */ |
| 31 | + secs = value / MSEC_PER_SEC; |
| 32 | + leftover = value - (secs * MSEC_PER_SEC); |
| 33 | + nsecs = (int64_t)leftover * NSEC_PER_MSEC; |
| 34 | + curr_value->it_value.tv_sec = (int32_t) secs; |
| 35 | + curr_value->it_value.tv_nsec = (int32_t) nsecs; |
| 36 | + |
| 37 | + /* converts period */ |
| 38 | + secs = period / MSEC_PER_SEC; |
| 39 | + leftover = period - (secs * MSEC_PER_SEC); |
| 40 | + nsecs = (int64_t)leftover * NSEC_PER_MSEC; |
| 41 | + curr_value->it_interval.tv_sec = (int32_t) secs; |
| 42 | + curr_value->it_interval.tv_nsec = (int32_t) nsecs; |
| 43 | + |
| 44 | + return 0; |
| 45 | +}; |
| 46 | + |
| 47 | +int timerfd_settime(int fd, int flags, const struct itimerspec *new_value, |
| 48 | + struct itimerspec *old_value) |
| 49 | +{ |
| 50 | + uint32_t period, duration, current; |
| 51 | + |
| 52 | + if (!timespec_is_valid(&new_value->it_interval) || |
| 53 | + !timespec_is_valid(&new_value->it_value)) { |
| 54 | + errno = EINVAL; |
| 55 | + return -1; |
| 56 | + } |
| 57 | + |
| 58 | + /* Save time to expire and old reload value. */ |
| 59 | + if (old_value != NULL) { |
| 60 | + timerfd_gettime(fd, old_value); |
| 61 | + } |
| 62 | + |
| 63 | + /* Calculate timer duration */ |
| 64 | + duration = ts_to_ms(&(new_value->it_value)); |
| 65 | + |
| 66 | + /* Calculate timer period */ |
| 67 | + period = ts_to_ms(&(new_value->it_interval)); |
| 68 | + |
| 69 | + if ((flags & TFD_TIMER_ABSTIME) != 0) { |
| 70 | + zvfs_timerfd_gettime(fd, ¤t, NULL); |
| 71 | + |
| 72 | + if (current >= duration) { |
| 73 | + duration = 0U; |
| 74 | + } else { |
| 75 | + duration -= current; |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + return zvfs_timerfd_settime(fd, K_MSEC(duration), K_MSEC(period)); |
| 80 | +} |
0 commit comments