| 1 |
/* SPDX-License-Identifier: LGPL-2.1-or-later */ |
| 2 |
|
| 3 |
#include <fcntl.h> |
| 4 |
#include <linux/rtc.h> |
| 5 |
#include <sys/ioctl.h> |
| 6 |
#include <time.h> |
| 7 |
|
| 8 |
#include "errno-util.h" |
| 9 |
#include "fd-util.h" |
| 10 |
#include "hwclock-util.h" |
| 11 |
|
| 12 |
int hwclock_get(struct tm *tm /* input + output! */) { |
| 13 |
_cleanup_close_ int fd = -EBADF; |
| 14 |
|
| 15 |
assert(tm); |
| 16 |
|
| 17 |
fd = open("/dev/rtc", O_RDONLY|O_CLOEXEC); |
| 18 |
if (fd < 0) |
| 19 |
return -errno; |
| 20 |
|
| 21 |
/* This leaves the timezone fields of struct ret uninitialized! */ |
| 22 |
if (ioctl(fd, RTC_RD_TIME, tm) < 0) |
| 23 |
/* Some drivers return -EINVAL in case the time could not be kept, i.e. power loss |
| 24 |
* happened. Let's turn that into a clearly recognizable error */ |
| 25 |
return errno == EINVAL ? -ENODATA : -errno; |
| 26 |
|
| 27 |
/* We don't know daylight saving, so we reset this in order not to confuse mktime(). */ |
| 28 |
tm->tm_isdst = -1; |
| 29 |
|
| 30 |
return 0; |
| 31 |
} |
| 32 |
|
| 33 |
int hwclock_set(const struct tm *tm) { |
| 34 |
_cleanup_close_ int fd = -EBADF; |
| 35 |
|
| 36 |
assert(tm); |
| 37 |
|
| 38 |
fd = open("/dev/rtc", O_RDONLY|O_CLOEXEC); |
| 39 |
if (fd < 0) |
| 40 |
return -errno; |
| 41 |
|
| 42 |
return RET_NERRNO(ioctl(fd, RTC_SET_TIME, tm)); |
| 43 |
} |