blob: 6f47d82522baf83d0041eb2cbbef29dd28e57cfb [file] [log] [blame]
Heinrich Schuchardt04ded002020-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>
Heinrich Schuchardta41437e2020-10-30 03:27:22 +010011#include <env.h>
Heinrich Schuchardt04ded002020-10-22 23:52:14 +020012#include <rtc.h>
Pali Rohár6e1f0852021-08-02 15:18:38 +020013#include <timestamp.h>
Heinrich Schuchardt04ded002020-10-22 23:52:14 +020014
15/**
16 * struct emul_rtc - private data for emulated RTC driver
17 */
18struct emul_rtc {
19 /**
20 * @offset_us: microseconds from 1970-01-01 to timer_get_us() base
21 */
22 u64 offset_us;
23 /**
24 * @isdst: daylight saving time
25 */
26 int isdst;
27};
28
29static int emul_rtc_get(struct udevice *dev, struct rtc_time *time)
30{
31 struct emul_rtc *priv = dev_get_priv(dev);
32 u64 now;
33
Heinrich Schuchardt04ded002020-10-22 23:52:14 +020034 now = timer_get_us() + priv->offset_us;
35 do_div(now, 1000000);
36 rtc_to_tm(now, time);
37 time->tm_isdst = priv->isdst;
38
39 return 0;
40}
41
42static int emul_rtc_set(struct udevice *dev, const struct rtc_time *time)
43{
44 struct emul_rtc *priv = dev_get_priv(dev);
45
46 if (time->tm_year < 1970)
47 return -EINVAL;
48
49 priv->offset_us = rtc_mktime(time) * 1000000ULL - timer_get_us();
50
51 if (time->tm_isdst > 0)
52 priv->isdst = 1;
53 else if (time->tm_isdst < 0)
54 priv->isdst = -1;
55 else
56 priv->isdst = 0;
57
58 return 0;
59}
60
Heinrich Schuchardt05b06d72020-10-30 03:05:47 +010061int emul_rtc_probe(struct udevice *dev)
62{
63 struct emul_rtc *priv = dev_get_priv(dev);
Heinrich Schuchardta41437e2020-10-30 03:27:22 +010064 const char *epoch_str;
65 u64 epoch;
66
67 epoch_str = env_get("rtc_emul_epoch");
Heinrich Schuchardt05b06d72020-10-30 03:05:47 +010068
Heinrich Schuchardta41437e2020-10-30 03:27:22 +010069 if (epoch_str) {
70 epoch = simple_strtoull(epoch_str, NULL, 10);
71 } else {
72 /* Use the build date as initial time */
73 epoch = U_BOOT_EPOCH;
74 }
75 priv->offset_us = epoch * 1000000ULL - timer_get_us();
Heinrich Schuchardt05b06d72020-10-30 03:05:47 +010076 priv->isdst = -1;
77
78 return 0;
79}
80
Heinrich Schuchardt04ded002020-10-22 23:52:14 +020081static const struct rtc_ops emul_rtc_ops = {
82 .get = emul_rtc_get,
83 .set = emul_rtc_set,
84};
85
86U_BOOT_DRIVER(rtc_emul) = {
87 .name = "rtc_emul",
88 .id = UCLASS_RTC,
89 .ops = &emul_rtc_ops,
Heinrich Schuchardt05b06d72020-10-30 03:05:47 +010090 .probe = emul_rtc_probe,
Simon Glass8a2b47f2020-12-03 16:55:17 -070091 .priv_auto = sizeof(struct emul_rtc),
Heinrich Schuchardt04ded002020-10-22 23:52:14 +020092};
93
Simon Glass1d8364a2020-12-28 20:34:54 -070094U_BOOT_DRVINFO(rtc_emul) = {
Heinrich Schuchardt04ded002020-10-22 23:52:14 +020095 .name = "rtc_emul",
96};