File: rtc.c

package info (click to toggle)
finit 4.14-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,216 kB
  • sloc: ansic: 17,060; sh: 6,281; makefile: 532
file content (353 lines) | stat: -rw-r--r-- 7,345 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
/* Save and restore RTC using hwclock
 *
 * Copyright (c) 2012-2025  Joachim Wiberg <troglobit@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include "config.h"

#include <time.h>
#include <sys/ioctl.h>
#include <linux/rtc.h>
#ifdef _LIBITE_LITE
# include <libite/lite.h>
#else
# include <lite/lite.h>
#endif

#include "finit.h"
#include "helpers.h"
#include "plugin.h"
#include "private.h"
#include "conf.h"
#include "log.h"

/*
 * Kernel RTC driver validates against this date for sanity check.  The
 * on NTP sync the driver can also update the RTC every 11 mins.  We use
 * the same update interval to handle manual time set and file save.
 */
#define RTC_TIMESTAMP_BEGIN_2000 "2000-01-01 00:00:00"
#define RTC_FMT                  "%Y-%m-%d %H:%M:%S"
#define RTC_PERIOD               (11 * 60 * 1000)

#ifdef  RTC_TIMESTAMP_CUSTOM
static char  *rtc_timestamp     = RTC_TIMESTAMP_CUSTOM;
#else
static char  *rtc_timestamp     = RTC_TIMESTAMP_BEGIN_2000;
#endif
static time_t rtc_date_fallback = 946684800LL;

static char  *rtc_file          = RTC_FILE;
static uev_t  rtc_timer;


static void tz_set(char *tz, size_t len)
{
	char *ptr;

	ptr = getenv("TZ");
	if (!ptr)
		memset(tz, 0, len);
	else
		strlcpy(tz, ptr, len);

	setenv("TZ", "UTC0", 1);
	tzset();
}

static void tz_restore(char *tz)
{
	if (!tz || !tz[0])
		unsetenv("TZ");
	else
		setenv("TZ", tz, 1);
	tzset();
}

static int time_set(struct tm *tm)
{
	struct tm fallback = { 0 };
	struct timeval tv = { 0 };
	char tz[128];
	int rc = 0;

	tz_set(tz, sizeof(tz));

	if (!tm) {
		logit(LOG_NOTICE, "Resetting system clock to kernel default, %s.", rtc_timestamp);
		tm = &fallback;

		/* Attempt to set RTC to a sane value ... */
		tv.tv_sec = rtc_date_fallback;
		if (!gmtime_r(&tv.tv_sec, tm)) {
			rc = 1;
			goto out;
		}
	}

	tm->tm_isdst = -1; /* Use tzdata to figure it out, please. */
	tv.tv_sec = mktime(tm);
	if (tv.tv_sec == (time_t)-1 || tv.tv_sec < rtc_date_fallback) {
		errno = EINVAL;
		rc = 2;
	} else {
		if (settimeofday(&tv, NULL) == -1)
			rc = 1;
	}
out:
	tz_restore(tz);
	return rc;
}

static int time_get(struct tm *tm)
{
	struct timeval tv = { 0 };
	char tz[128];
	int rc = 0;

	tz_set(tz, sizeof(tz));

	rc = gettimeofday(&tv, NULL);
	if (rc < 0 || tv.tv_sec < rtc_date_fallback)
		rc = 2;
	else
		gmtime_r(&tv.tv_sec, tm);

	tz_restore(tz);

	return rc;
}

static void file_save(void *arg)
{
	struct tm tm = { 0 };
	int rc = 0;
	FILE *fp;

	if (!rtc_file)
		return;

	fp = fopen(rtc_file, "w");
	if (!fp) {
		logit(LOG_WARNING, "Failed saving system clock to %s, code %d: %s",
		      rtc_file, errno, strerror(errno));
		return;
	}

	if ((rc = time_get(&tm))) {
		logit(LOG_WARNING, "System clock invalid, before %s, not saving", rtc_timestamp);
		print_desc(NULL, "System clock invalid, skipping");
	} else {
		char buf[32] = { 0 };

		print_desc(NULL, "Saving system clock to file");
		strftime(buf, sizeof(buf), RTC_FMT, &tm);
		fprintf(fp, "%s\n", buf);
	}

	print(rc, NULL);
	fclose(fp);
}

static void file_restore(void *arg)
{
	struct tm tm = { 0 };
	int rc = 1;
	FILE *fp;

	if (!rtc_file) {
		logit(LOG_NOTICE, "System has no RTC (missing driver?), skipping restore.");
		return;
	}

	print_desc(NULL, "Restoring system clock from backup");

	fp = fopen(rtc_file, "r");
	if (fp) {
		char buf[32];

		if (fgets(buf, sizeof(buf), fp)) {
			chomp(buf);
			strptime(buf, RTC_FMT, &tm);
			rc = time_set(&tm);
		}
		fclose(fp);
	} else
		logit(LOG_WARNING, "Missing %s", rtc_file);

	if (rc) {
		time_set(NULL);
		rc = 2;
	}

	print(rc, NULL);
}

static int rtc_open(void)
{
	char *alt[] = {
		"/dev/rtc",
		"/dev/rtc0",
		"/dev/misc/rtc"
	};
	size_t i;
	int fd;

	for (i = 0; i < NELEMS(alt); i++) {
		fd = open(alt[i], O_RDONLY);
		if (fd < 0)
			continue;

		return fd;
	}

	return -1;
}

static void rtc_save(void *arg)
{
	struct tm tm = { 0 };
	int fd, rc = 0;

	if (rescue) {
		dbg("Skipping %s plugin in rescue mode.", __FILE__);
		return;
	}

	fd = rtc_open();
	if (fd < 0)
		return;

	if ((rc = time_get(&tm))) {
		print_desc(NULL, "System clock invalid, not saving to RTC");
	} else {
		print_desc(NULL, "Saving system clock (UTC) to RTC");
		rc = ioctl(fd, RTC_SET_TIME, &tm);
	}

	if (rc && errno == EINVAL) {
		logit(LOG_WARNING, "System clock invalid, before %s, not saving to RTC", rtc_timestamp);
		rc = 2;
	}

	print(rc, NULL);
	close(fd);
}

static void rtc_restore(void *arg)
{
	struct tm tm = { 0 };
	int fd, rc = 0;

	if (rescue) {
		dbg("Skipping %s plugin in rescue mode.", __FILE__);
		return;
	}

	fd = rtc_open();
	if (fd < 0) {
		file_restore(arg);
		return;
	}

	if ((rc = ioctl(fd, RTC_RD_TIME, &tm)) < 0) {
		char msg[120];

		snprintf(msg, sizeof(msg), "Failed restoring system clock, %s",
			 EINVAL == errno ? "RTC time is too old"   :
			 ENOENT == errno ? "RTC has no saved time" : "see log for details");
		print_desc(NULL, msg);
	} else {
		print_desc(NULL, "Restoring system clock (UTC) from RTC");
		rc = time_set(&tm);
	}

	if (rc) {
		logit(LOG_WARNING, "Failed restoring system clock from RTC.");
		if (EINVAL == errno)
			logit(LOG_WARNING, "RTC time is too old (before %s)", rtc_timestamp);
		else if (ENOENT == errno)
			logit(LOG_WARNING, "RTC has no previously saved (valid) time.");
		else
			logit(LOG_WARNING, "RTC error code %d: %s", errno, strerror(errno));

		print(2, NULL);

		/* Try restoring from last save game */
		if (rtc_file)
			file_restore(arg);
	} else
		print(0, NULL);

	close(fd);
}


static void save(void *arg)
{
	rtc_save(arg);
	file_save(arg);
}

static void update(uev_t *w, void *arg, int events)
{
	save(arg);
}


static plugin_t plugin = {
	.name = __FILE__,
	.hook[HOOK_BASEFS_UP] = {
		.cb  = rtc_restore
	},
	.hook[HOOK_SHUTDOWN] = {
		.cb  = save
	}
};

PLUGIN_INIT(__init)
{
	struct tm tm = { 0 };

	if (!strptime(rtc_timestamp, RTC_FMT, &tm)) {
		logit(LOG_WARNING, "Invalid restore date '%s', reverting to '%s'",
		      rtc_timestamp, RTC_TIMESTAMP_BEGIN_2000);
		rtc_timestamp = RTC_TIMESTAMP_BEGIN_2000;
	} else
		rtc_date_fallback = mktime(&tm);

	uev_timer_init(ctx, &rtc_timer, update, NULL, RTC_PERIOD, RTC_PERIOD);

	plugin_register(&plugin);
}

PLUGIN_EXIT(__exit)
{
	uev_timer_stop(&rtc_timer);
	plugin_unregister(&plugin);
}

/**
 * Local Variables:
 *  indent-tabs-mode: t
 *  c-file-style: "linux"
 * End:
 */