blob: db89fa3a358c7ba16df4d46cdc2b594f7376652b [file] [log] [blame]
Philipp Tomsich482734a2018-11-27 23:00:19 +01001// SPDX-License-Identifier: GPL-2.0+
2/*
3 * (C) Copyright 2018 Theobroma Systems Design und Consulting GmbH
4 */
5
6#include <common.h>
7#include <bootcount.h>
8#include <dm.h>
9#include <rtc.h>
10
11static const u8 bootcount_magic = 0xbc;
12
13struct bootcount_rtc_priv {
14 struct udevice *rtc;
15 u32 offset;
16};
17
18static int bootcount_rtc_set(struct udevice *dev, const u32 a)
19{
20 struct bootcount_rtc_priv *priv = dev_get_priv(dev);
21 const u16 val = bootcount_magic << 8 | (a & 0xff);
22
23 if (rtc_write16(priv->rtc, priv->offset, val) < 0) {
24 debug("%s: rtc_write16 failed\n", __func__);
25 return -EIO;
26 }
27
28 return 0;
29}
30
31static int bootcount_rtc_get(struct udevice *dev, u32 *a)
32{
33 struct bootcount_rtc_priv *priv = dev_get_priv(dev);
34 u16 val;
35
36 if (rtc_read16(priv->rtc, priv->offset, &val) < 0) {
37 debug("%s: rtc_write16 failed\n", __func__);
38 return -EIO;
39 }
40
41 if (val >> 8 == bootcount_magic) {
42 *a = val & 0xff;
43 return 0;
44 }
45
46 debug("%s: bootcount magic does not match on %04x\n", __func__, val);
47 return -EIO;
48}
49
50static int bootcount_rtc_probe(struct udevice *dev)
51{
52 struct ofnode_phandle_args phandle_args;
53 struct bootcount_rtc_priv *priv = dev_get_priv(dev);
54 struct udevice *rtc;
55
56 if (dev_read_phandle_with_args(dev, "rtc", NULL, 0, 0, &phandle_args)) {
57 debug("%s: rtc backing device not specified\n", dev->name);
58 return -ENOENT;
59 }
60
61 if (uclass_get_device_by_ofnode(UCLASS_RTC, phandle_args.node, &rtc)) {
62 debug("%s: could not get backing device\n", dev->name);
63 return -ENODEV;
64 }
65
66 priv->rtc = rtc;
67 priv->offset = dev_read_u32_default(dev, "offset", 0);
68
69 return 0;
70}
71
72static const struct bootcount_ops bootcount_rtc_ops = {
73 .get = bootcount_rtc_get,
74 .set = bootcount_rtc_set,
75};
76
77static const struct udevice_id bootcount_rtc_ids[] = {
78 { .compatible = "u-boot,bootcount-rtc" },
79 { }
80};
81
82U_BOOT_DRIVER(bootcount_rtc) = {
83 .name = "bootcount-rtc",
84 .id = UCLASS_BOOTCOUNT,
85 .priv_auto_alloc_size = sizeof(struct bootcount_rtc_priv),
86 .probe = bootcount_rtc_probe,
87 .of_match = bootcount_rtc_ids,
88 .ops = &bootcount_rtc_ops,
89};