blob: c98c24bbb3d2c9d9f043b155e454ee11b18f193e [file] [log] [blame]
Heinrich Schuchardt87e99632020-10-22 23:52:14 +02001// SPDX-License-Identifier: GPL-2.0+
2/*
3 * Copyright 2020, Heinrich Schuchardt <xypron.glpk@gmx.de>
4 *
5 * This driver emulates a real time clock based on timer ticks.
6 */
7
8#include <common.h>
9#include <div64.h>
10#include <dm.h>
11#include <generated/timestamp_autogenerated.h>
12#include <rtc.h>
13
14/**
15 * struct emul_rtc - private data for emulated RTC driver
16 */
17struct emul_rtc {
18 /**
19 * @offset_us: microseconds from 1970-01-01 to timer_get_us() base
20 */
21 u64 offset_us;
22 /**
23 * @isdst: daylight saving time
24 */
25 int isdst;
26};
27
28static int emul_rtc_get(struct udevice *dev, struct rtc_time *time)
29{
30 struct emul_rtc *priv = dev_get_priv(dev);
31 u64 now;
32
33 if (!priv->offset_us) {
34 /* Use the build date as initial time */
35 priv->offset_us = U_BOOT_EPOCH * 1000000ULL - timer_get_us();
36 priv->isdst = -1;
37 }
38
39 now = timer_get_us() + priv->offset_us;
40 do_div(now, 1000000);
41 rtc_to_tm(now, time);
42 time->tm_isdst = priv->isdst;
43
44 return 0;
45}
46
47static int emul_rtc_set(struct udevice *dev, const struct rtc_time *time)
48{
49 struct emul_rtc *priv = dev_get_priv(dev);
50
51 if (time->tm_year < 1970)
52 return -EINVAL;
53
54 priv->offset_us = rtc_mktime(time) * 1000000ULL - timer_get_us();
55
56 if (time->tm_isdst > 0)
57 priv->isdst = 1;
58 else if (time->tm_isdst < 0)
59 priv->isdst = -1;
60 else
61 priv->isdst = 0;
62
63 return 0;
64}
65
66static const struct rtc_ops emul_rtc_ops = {
67 .get = emul_rtc_get,
68 .set = emul_rtc_set,
69};
70
71U_BOOT_DRIVER(rtc_emul) = {
72 .name = "rtc_emul",
73 .id = UCLASS_RTC,
74 .ops = &emul_rtc_ops,
75 .priv_auto_alloc_size = sizeof(struct emul_rtc),
76};
77
78U_BOOT_DEVICE(rtc_emul) = {
79 .name = "rtc_emul",
80};