1/*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 1988 University of Utah.
5 * Copyright (c) 1982, 1990, 1993
6 *	The Regents of the University of California.
7 * Copyright (c) 2011 The FreeBSD Foundation
8 * All rights reserved.
9 *
10 * This code is derived from software contributed to Berkeley by
11 * the Systems Programming Group of the University of Utah Computer
12 * Science Department.
13 *
14 * Portions of this software were developed by Julien Ridoux at the University
15 * of Melbourne under sponsorship from the FreeBSD Foundation.
16 *
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
19 * are met:
20 * 1. Redistributions of source code must retain the above copyright
21 *    notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 *    notice, this list of conditions and the following disclaimer in the
24 *    documentation and/or other materials provided with the distribution.
25 * 3. Neither the name of the University nor the names of its contributors
26 *    may be used to endorse or promote products derived from this software
27 *    without specific prior written permission.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
30 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
31 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
32 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
33 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
35 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
37 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
38 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39 * SUCH DAMAGE.
40 *
41 *	from: Utah $Hdr: clock.c 1.18 91/01/21$
42 *	from: NetBSD: clock_subr.c,v 1.6 2001/07/07 17:04:02 thorpej Exp
43 *	and
44 *	from: src/sys/i386/isa/clock.c,v 1.176 2001/09/04
45 */
46
47/*
48 * Helpers for time-of-day clocks. This is useful for architectures that need
49 * support multiple models of such clocks, and generally serves to make the
50 * code more machine-independent.
51 * If the clock in question can also be used as a time counter, the driver
52 * needs to initiate this.
53 * This code is not yet used by all architectures.
54 */
55
56#include <sys/cdefs.h>
57#include "opt_ffclock.h"
58
59#include <sys/param.h>
60#include <sys/systm.h>
61#include <sys/kernel.h>
62#include <sys/bus.h>
63#include <sys/clock.h>
64#include <sys/lock.h>
65#include <sys/malloc.h>
66#include <sys/sx.h>
67#include <sys/sysctl.h>
68#include <sys/taskqueue.h>
69#ifdef FFCLOCK
70#include <sys/timeffc.h>
71#endif
72#include <sys/timetc.h>
73
74#include "clock_if.h"
75
76static int show_io;
77SYSCTL_INT(_debug, OID_AUTO, clock_show_io, CTLFLAG_RWTUN, &show_io, 0,
78    "Enable debug printing of RTC clock I/O; 1=reads, 2=writes, 3=both.");
79
80static int sysctl_clock_do_io(SYSCTL_HANDLER_ARGS);
81SYSCTL_PROC(_debug, OID_AUTO, clock_do_io,
82    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, 0, 0, sysctl_clock_do_io, "I",
83    "Trigger one-time IO on RTC clocks; 1=read (and discard), 2=write");
84
85/* XXX: should be kern. now, it's no longer machdep.  */
86static int disable_rtc_set;
87SYSCTL_INT(_machdep, OID_AUTO, disable_rtc_set, CTLFLAG_RW, &disable_rtc_set,
88    0, "Disallow adjusting time-of-day clock");
89
90/*
91 * An instance of a realtime clock.  A list of these tracks all the registered
92 * clocks in the system.
93 *
94 * The resadj member is used to apply a "resolution adjustment" equal to half
95 * the clock's resolution, which is useful mainly on clocks with a whole-second
96 * resolution.  Because the clock truncates the fractional part, adding half the
97 * resolution performs 4/5 rounding.  The same adjustment is applied to the
98 * times returned from clock_gettime(), because the fraction returned will
99 * always be zero, but on average the actual fraction at the time of the call
100 * should be about .5.
101 */
102struct rtc_instance {
103	device_t	clockdev;
104	int		resolution;
105	int		flags;
106	u_int		schedns;
107	struct timespec resadj;
108	struct timeout_task
109			stask;
110	LIST_ENTRY(rtc_instance)
111			rtc_entries;
112};
113
114/*
115 * Clocks are updated using a task running on taskqueue_thread.
116 */
117static void settime_task_func(void *arg, int pending);
118
119/*
120 * Registered clocks are kept in a list which is sorted by resolution; the more
121 * accurate clocks get the first shot at providing the time.
122 */
123LIST_HEAD(rtc_listhead, rtc_instance);
124static struct rtc_listhead rtc_list = LIST_HEAD_INITIALIZER(rtc_list);
125static struct sx rtc_list_lock;
126SX_SYSINIT(rtc_list_lock_init, &rtc_list_lock, "rtc list");
127
128/*
129 * On the task thread, invoke the clock_settime() method of the clock.  Do so
130 * holding no locks, so that clock drivers are free to do whatever kind of
131 * locking or sleeping they need to.
132 */
133static void
134settime_task_func(void *arg, int pending)
135{
136	struct timespec ts;
137	struct rtc_instance *rtc;
138	int error;
139
140	rtc = arg;
141	if (!(rtc->flags & CLOCKF_SETTIME_NO_TS)) {
142		getnanotime(&ts);
143		if (!(rtc->flags & CLOCKF_SETTIME_NO_ADJ)) {
144			ts.tv_sec -= utc_offset();
145			timespecadd(&ts, &rtc->resadj, &ts);
146		}
147	} else {
148		ts.tv_sec  = 0;
149		ts.tv_nsec = 0;
150	}
151	error = CLOCK_SETTIME(rtc->clockdev, &ts);
152	if (error != 0 && bootverbose)
153		device_printf(rtc->clockdev, "CLOCK_SETTIME error %d\n", error);
154}
155
156static void
157clock_dbgprint_hdr(device_t dev, int rw)
158{
159	struct timespec now;
160
161	getnanotime(&now);
162	device_printf(dev, "%s at ", (rw & CLOCK_DBG_READ) ? "read " : "write");
163	clock_print_ts(&now, 9);
164	printf(": ");
165}
166
167void
168clock_dbgprint_bcd(device_t dev, int rw, const struct bcd_clocktime *bct)
169{
170
171	if (show_io & rw) {
172		clock_dbgprint_hdr(dev, rw);
173		clock_print_bcd(bct, 9);
174		printf("\n");
175	}
176}
177
178void
179clock_dbgprint_ct(device_t dev, int rw, const struct clocktime *ct)
180{
181
182	if (show_io & rw) {
183		clock_dbgprint_hdr(dev, rw);
184		clock_print_ct(ct, 9);
185		printf("\n");
186	}
187}
188
189void
190clock_dbgprint_err(device_t dev, int rw, int err)
191{
192
193	if (show_io & rw) {
194		clock_dbgprint_hdr(dev, rw);
195		printf("error = %d\n", err);
196	}
197}
198
199void
200clock_dbgprint_ts(device_t dev, int rw, const struct timespec *ts)
201{
202
203	if (show_io & rw) {
204		clock_dbgprint_hdr(dev, rw);
205		clock_print_ts(ts, 9);
206		printf("\n");
207	}
208}
209
210void
211clock_register_flags(device_t clockdev, long resolution, int flags)
212{
213	struct rtc_instance *rtc, *newrtc;
214
215	newrtc = malloc(sizeof(*newrtc), M_DEVBUF, M_WAITOK);
216	newrtc->clockdev = clockdev;
217	newrtc->resolution = (int)resolution;
218	newrtc->flags = flags;
219	newrtc->schedns = 0;
220	newrtc->resadj.tv_sec  = newrtc->resolution / 2 / 1000000;
221	newrtc->resadj.tv_nsec = newrtc->resolution / 2 % 1000000 * 1000;
222	TIMEOUT_TASK_INIT(taskqueue_thread, &newrtc->stask, 0,
223		    settime_task_func, newrtc);
224
225	sx_xlock(&rtc_list_lock);
226	if (LIST_EMPTY(&rtc_list)) {
227		LIST_INSERT_HEAD(&rtc_list, newrtc, rtc_entries);
228	} else {
229		LIST_FOREACH(rtc, &rtc_list, rtc_entries) {
230			if (rtc->resolution > newrtc->resolution) {
231				LIST_INSERT_BEFORE(rtc, newrtc, rtc_entries);
232				break;
233			} else if (LIST_NEXT(rtc, rtc_entries) == NULL) {
234				LIST_INSERT_AFTER(rtc, newrtc, rtc_entries);
235				break;
236			}
237		}
238	}
239	sx_xunlock(&rtc_list_lock);
240
241	device_printf(clockdev,
242	    "registered as a time-of-day clock, resolution %d.%6.6ds\n",
243	    newrtc->resolution / 1000000, newrtc->resolution % 1000000);
244}
245
246void
247clock_register(device_t dev, long res)
248{
249
250	clock_register_flags(dev, res, 0);
251}
252
253void
254clock_unregister(device_t clockdev)
255{
256	struct rtc_instance *rtc, *tmp;
257
258	sx_xlock(&rtc_list_lock);
259	LIST_FOREACH_SAFE(rtc, &rtc_list, rtc_entries, tmp) {
260		if (rtc->clockdev == clockdev) {
261			LIST_REMOVE(rtc, rtc_entries);
262			break;
263		}
264	}
265	sx_xunlock(&rtc_list_lock);
266	if (rtc != NULL) {
267		taskqueue_cancel_timeout(taskqueue_thread, &rtc->stask, NULL);
268		taskqueue_drain_timeout(taskqueue_thread, &rtc->stask);
269		free(rtc, M_DEVBUF);
270	}
271}
272
273void
274clock_schedule(device_t clockdev, u_int offsetns)
275{
276	struct rtc_instance *rtc;
277
278	sx_xlock(&rtc_list_lock);
279	LIST_FOREACH(rtc, &rtc_list, rtc_entries) {
280		if (rtc->clockdev == clockdev) {
281			rtc->schedns = offsetns;
282			break;
283		}
284	}
285	sx_xunlock(&rtc_list_lock);
286}
287
288static int
289read_clocks(struct timespec *ts, bool debug_read)
290{
291	struct rtc_instance *rtc;
292	int error;
293
294	error = ENXIO;
295	sx_xlock(&rtc_list_lock);
296	LIST_FOREACH(rtc, &rtc_list, rtc_entries) {
297		if ((error = CLOCK_GETTIME(rtc->clockdev, ts)) != 0)
298			continue;
299		if (ts->tv_sec < 0 || ts->tv_nsec < 0) {
300			error = EINVAL;
301			continue;
302		}
303		if (!(rtc->flags & CLOCKF_GETTIME_NO_ADJ)) {
304			timespecadd(ts, &rtc->resadj, ts);
305			ts->tv_sec += utc_offset();
306		}
307		if (!debug_read) {
308			if (bootverbose)
309				device_printf(rtc->clockdev,
310				    "providing initial system time\n");
311			break;
312		}
313	}
314	sx_xunlock(&rtc_list_lock);
315	return (error);
316}
317
318/*
319 * Initialize the system time.  Must be called from a context which does not
320 * restrict any locking or sleeping that clock drivers may need to do.
321 *
322 * First attempt to get the time from a registered realtime clock.  The clocks
323 * are queried in order of resolution until one provides the time.  If no clock
324 * can provide the current time, use the 'base' time provided by the caller, if
325 * non-zero.  The 'base' time is potentially highly inaccurate, such as the last
326 * known good value of the system clock, or even a filesystem last-updated
327 * timestamp.  It is used to prevent system time from appearing to move
328 * backwards in logs.
329 */
330void
331inittodr(time_t base)
332{
333	struct timespec ts;
334	int error;
335
336	error = read_clocks(&ts, false);
337
338	/*
339	 * Do not report errors from each clock; it is expected that some clocks
340	 * cannot provide results in some situations.  Only report problems when
341	 * no clocks could provide the time.
342	 */
343	if (error != 0) {
344		switch (error) {
345		case ENXIO:
346			printf("Warning: no time-of-day clock registered, ");
347			break;
348		case EINVAL:
349			printf("Warning: bad time from time-of-day clock, ");
350			break;
351		default:
352			printf("Error reading time-of-day clock (%d), ", error);
353			break;
354		}
355		printf("system time will not be set accurately\n");
356		ts.tv_sec  = (base > 0) ? base : -1;
357		ts.tv_nsec = 0;
358	}
359
360	if (ts.tv_sec >= 0) {
361		tc_setclock(&ts);
362#ifdef FFCLOCK
363		ffclock_reset_clock(&ts);
364#endif
365	}
366}
367
368/*
369 * Write system time back to all registered clocks, unless disabled by admin.
370 * This can be called from a context that restricts locking and/or sleeping; the
371 * actual updating is done asynchronously on a task thread.
372 */
373void
374resettodr(void)
375{
376	struct timespec now;
377	struct rtc_instance *rtc;
378	sbintime_t sbt;
379	long waitns;
380
381	if (disable_rtc_set)
382		return;
383
384	sx_xlock(&rtc_list_lock);
385	LIST_FOREACH(rtc, &rtc_list, rtc_entries) {
386		if (rtc->schedns != 0) {
387			getnanotime(&now);
388			waitns = rtc->schedns - now.tv_nsec;
389			if (waitns < 0)
390				waitns += 1000000000;
391			sbt = nstosbt(waitns);
392		} else
393			sbt = 0;
394		taskqueue_enqueue_timeout_sbt(taskqueue_thread,
395		    &rtc->stask, -sbt, 0, C_PREL(31));
396	}
397	sx_xunlock(&rtc_list_lock);
398}
399
400static int
401sysctl_clock_do_io(SYSCTL_HANDLER_ARGS)
402{
403	struct timespec ts_discard;
404	int error, value;
405
406	value = 0;
407	error = sysctl_handle_int(oidp, &value, 0, req);
408	if (error != 0 || req->newptr == NULL)
409		return (error);
410
411	switch (value) {
412	case CLOCK_DBG_READ:
413		if (read_clocks(&ts_discard, true) == ENXIO)
414			printf("No registered RTC clocks\n");
415		break;
416	case CLOCK_DBG_WRITE:
417		resettodr();
418		break;
419	default:
420                return (EINVAL);
421	}
422
423	return (0);
424}
425