blob: 209b4965c17d3e97c9c1fb5bf06cef9dd6857096 [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>
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
Heinrich Schuchardt04ded002020-10-22 23:52:14 +020033 now = timer_get_us() + priv->offset_us;
34 do_div(now, 1000000);
35 rtc_to_tm(now, time);
36 time->tm_isdst = priv->isdst;
37
38 return 0;
39}
40
41static int emul_rtc_set(struct udevice *dev, const struct rtc_time *time)
42{
43 struct emul_rtc *priv = dev_get_priv(dev);
44
45 if (time->tm_year < 1970)
46 return -EINVAL;
47
48 priv->offset_us = rtc_mktime(time) * 1000000ULL - timer_get_us();
49
50 if (time->tm_isdst > 0)
51 priv->isdst = 1;
52 else if (time->tm_isdst < 0)
53 priv->isdst = -1;
54 else
55 priv->isdst = 0;
56
57 return 0;
58}
59
Heinrich Schuchardt05b06d72020-10-30 03:05:47 +010060int emul_rtc_probe(struct udevice *dev)
61{
62 struct emul_rtc *priv = dev_get_priv(dev);
63
64 /* Use the build date as initial time */
65 priv->offset_us = U_BOOT_EPOCH * 1000000ULL - timer_get_us();
66 priv->isdst = -1;
67
68 return 0;
69}
70
Heinrich Schuchardt04ded002020-10-22 23:52:14 +020071static const struct rtc_ops emul_rtc_ops = {
72 .get = emul_rtc_get,
73 .set = emul_rtc_set,
74};
75
76U_BOOT_DRIVER(rtc_emul) = {
77 .name = "rtc_emul",
78 .id = UCLASS_RTC,
79 .ops = &emul_rtc_ops,
Heinrich Schuchardt05b06d72020-10-30 03:05:47 +010080 .probe = emul_rtc_probe,
Heinrich Schuchardt04ded002020-10-22 23:52:14 +020081 .priv_auto_alloc_size = sizeof(struct emul_rtc),
82};
83
84U_BOOT_DEVICE(rtc_emul) = {
85 .name = "rtc_emul",
86};