1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (C) 2020 Unisoc Communications Inc.
4 */
5
6 /*\
7 * [Description]
8 *
9 * RTC device set time function test.
10 *
11 * [Algorithm]
12 *
13 * - Save RTC time
14 * - Set RTC time
15 * - Read the RTC time back
16 * - Check if the set time and the read time are identical
17 * - Restore RTC time
18 */
19
20 #include <stdio.h>
21 #include "tst_rtctime.h"
22 #include "tst_wallclock.h"
23 #include "tst_test.h"
24
25 static char *rtc_dev = "/dev/rtc";
26
rtctime_to_str(struct rtc_time * tm)27 static char *rtctime_to_str(struct rtc_time *tm)
28 {
29 static char rtctime_buf[128];
30
31 sprintf(rtctime_buf, "%04d-%02d-%02d %02d:%02d:%02d",
32 tm->tm_year + 1900,
33 tm->tm_mon + 1,
34 tm->tm_mday,
35 tm->tm_hour,
36 tm->tm_min,
37 tm->tm_sec);
38 return rtctime_buf;
39 }
40
rtc_tm_cmp(struct rtc_time * set_tm,struct rtc_time * read_tm)41 static int rtc_tm_cmp(struct rtc_time *set_tm, struct rtc_time *read_tm)
42 {
43 return !((set_tm->tm_sec == read_tm->tm_sec)
44 && (set_tm->tm_min == read_tm->tm_min)
45 && (set_tm->tm_hour == read_tm->tm_hour)
46 && (set_tm->tm_mday == read_tm->tm_mday)
47 && (set_tm->tm_mon == read_tm->tm_mon)
48 && (set_tm->tm_year == read_tm->tm_year));
49 }
50
set_rtc_test(void)51 static void set_rtc_test(void)
52 {
53 struct rtc_time read_tm;
54 int ret;
55
56 struct rtc_time set_tm = {
57 .tm_sec = 30,
58 .tm_min = 23,
59 .tm_hour = 13,
60 .tm_mday = 9,
61 .tm_mon = 9,
62 .tm_year = 120,
63 };
64
65 /* set rtc to 2020.10.9 13:23:30 */
66 tst_res(TINFO, "To set RTC date/time is: %s", rtctime_to_str(&set_tm));
67
68 ret = tst_rtc_settime(rtc_dev, &set_tm);
69 if (ret != 0) {
70 tst_res(TFAIL | TERRNO, "ioctl() RTC_SET_TIME");
71 return;
72 }
73
74 /* Read current RTC Time */
75 ret = tst_rtc_gettime(rtc_dev, &read_tm);
76 if (ret != 0) {
77 tst_res(TFAIL | TERRNO, "ioctl() RTC_RD_TIME");
78 return;
79 }
80 tst_res(TINFO, "read RTC date/time is: %s", rtctime_to_str(&read_tm));
81
82 if (rtc_tm_cmp(&set_tm, &read_tm)) {
83 tst_res(TFAIL, "RTC SET TEST");
84 return;
85 }
86 tst_res(TPASS, "The read RTC time is consistent with set time");
87
88 }
89
rtc_setup(void)90 static void rtc_setup(void)
91 {
92 int exists = access(rtc_dev, F_OK);
93
94 if (exists < 0)
95 tst_brk(TCONF, "RTC device %s not available", rtc_dev);
96
97 tst_rtc_clock_save(rtc_dev);
98 }
99
rtc_cleanup(void)100 static void rtc_cleanup(void)
101 {
102 tst_rtc_clock_restore(rtc_dev);
103 }
104
105 static struct tst_test test = {
106 .setup = rtc_setup,
107 .test_all = set_rtc_test,
108 .cleanup = rtc_cleanup,
109 .needs_root = 1,
110 };
111