#include <sys/param.h>
#include <sys/systm.h>
#include <sys/bus.h>
#include <sys/clock.h>
#include <sys/efi.h>
#include <sys/kernel.h>
#include <sys/module.h>
#include "clock_if.h"
static bool efirtc_zeroes_subseconds;
static struct timespec efirtc_resadj;
static const u_int us_per_s = 1000000;
static const u_int ns_per_s = 1000000000;
static const u_int ns_per_us = 1000;
static void
efirtc_identify(driver_t *driver, device_t parent)
{
if (efi_rt_ok() != 0)
return;
if (device_find_child(parent, "efirtc", DEVICE_UNIT_ANY) != NULL)
return;
if (BUS_ADD_CHILD(parent, 0, "efirtc", DEVICE_UNIT_ANY) == NULL)
device_printf(parent, "add child failed\n");
}
static int
efirtc_probe(device_t dev)
{
struct efi_tm tm;
int error;
if ((error = efi_get_time(&tm)) != 0) {
if (bootverbose)
device_printf(dev, "cannot read EFI realtime clock, "
"error %d\n", error);
return (error);
}
device_set_desc(dev, "EFI Realtime Clock");
return (BUS_PROBE_DEFAULT);
}
static int
efirtc_attach(device_t dev)
{
struct efi_tmcap tmcap;
long res;
int error;
bzero(&tmcap, sizeof(tmcap));
if ((error = efi_get_time_capabilities(&tmcap)) != 0) {
device_printf(dev, "cannot get EFI time capabilities");
return (error);
}
if (tmcap.tc_res == 0)
res = us_per_s;
else if (tmcap.tc_res > us_per_s)
res = 1;
else
res = us_per_s / tmcap.tc_res;
efirtc_resadj.tv_nsec = (res * ns_per_us) / 2;
efirtc_zeroes_subseconds = tmcap.tc_stz;
clock_register_flags(dev, res, CLOCKF_SETTIME_NO_ADJ);
if (efirtc_zeroes_subseconds)
clock_schedule(dev, ns_per_s - ns_per_us);
return (0);
}
static int
efirtc_detach(device_t dev)
{
clock_unregister(dev);
return (0);
}
static int
efirtc_gettime(device_t dev, struct timespec *ts)
{
struct clocktime ct;
struct efi_tm tm;
int error;
error = efi_get_time(&tm);
if (error != 0)
return (error);
ct.sec = tm.tm_sec;
ct.min = tm.tm_min;
ct.hour = tm.tm_hour;
ct.day = tm.tm_mday;
ct.mon = tm.tm_mon;
ct.year = tm.tm_year;
ct.nsec = tm.tm_nsec;
clock_dbgprint_ct(dev, CLOCK_DBG_READ, &ct);
return (clock_ct_to_ts(&ct, ts));
}
static int
efirtc_settime(device_t dev, struct timespec *ts)
{
struct clocktime ct;
struct efi_tm tm;
ts->tv_sec -= utc_offset();
if (!efirtc_zeroes_subseconds)
timespecadd(ts, &efirtc_resadj, ts);
clock_ts_to_ct(ts, &ct);
clock_dbgprint_ct(dev, CLOCK_DBG_WRITE, &ct);
bzero(&tm, sizeof(tm));
tm.tm_sec = ct.sec;
tm.tm_min = ct.min;
tm.tm_hour = ct.hour;
tm.tm_mday = ct.day;
tm.tm_mon = ct.mon;
tm.tm_year = ct.year;
tm.tm_nsec = ct.nsec;
return (efi_set_time(&tm));
}
static device_method_t efirtc_methods[] = {
DEVMETHOD(device_identify, efirtc_identify),
DEVMETHOD(device_probe, efirtc_probe),
DEVMETHOD(device_attach, efirtc_attach),
DEVMETHOD(device_detach, efirtc_detach),
DEVMETHOD(clock_gettime, efirtc_gettime),
DEVMETHOD(clock_settime, efirtc_settime),
DEVMETHOD_END
};
static driver_t efirtc_driver = {
"efirtc",
efirtc_methods,
0
};
DRIVER_MODULE(efirtc, nexus, efirtc_driver, 0, 0);
MODULE_VERSION(efirtc, 1);
MODULE_DEPEND(efirtc, efirt, 1, 1, 1);