xref: /freebsd/sys/kern/subr_rtc.c (revision f0cfa1b168014f56c02b83e5f28412cc5f78d117)
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: @(#)clock.c	8.2 (Berkeley) 1/12/94
43  *	from: NetBSD: clock_subr.c,v 1.6 2001/07/07 17:04:02 thorpej Exp
44  *	and
45  *	from: src/sys/i386/isa/clock.c,v 1.176 2001/09/04
46  */
47 
48 /*
49  * Helpers for time-of-day clocks. This is useful for architectures that need
50  * support multiple models of such clocks, and generally serves to make the
51  * code more machine-independent.
52  * If the clock in question can also be used as a time counter, the driver
53  * needs to initiate this.
54  * This code is not yet used by all architectures.
55  */
56 
57 #include <sys/cdefs.h>
58 __FBSDID("$FreeBSD$");
59 
60 #include "opt_ffclock.h"
61 
62 #include <sys/param.h>
63 #include <sys/systm.h>
64 #include <sys/kernel.h>
65 #include <sys/bus.h>
66 #include <sys/clock.h>
67 #include <sys/lock.h>
68 #include <sys/malloc.h>
69 #include <sys/sx.h>
70 #include <sys/sysctl.h>
71 #include <sys/taskqueue.h>
72 #ifdef FFCLOCK
73 #include <sys/timeffc.h>
74 #endif
75 #include <sys/timetc.h>
76 
77 #include "clock_if.h"
78 
79 /* XXX: should be kern. now, it's no longer machdep.  */
80 static int disable_rtc_set;
81 SYSCTL_INT(_machdep, OID_AUTO, disable_rtc_set, CTLFLAG_RW, &disable_rtc_set,
82     0, "Disallow adjusting time-of-day clock");
83 
84 /*
85  * An instance of a realtime clock.  A list of these tracks all the registered
86  * clocks in the system.
87  *
88  * The resadj member is used to apply a "resolution adjustment" equal to half
89  * the clock's resolution, which is useful mainly on clocks with a whole-second
90  * resolution.  Because the clock truncates the fractional part, adding half the
91  * resolution performs 4/5 rounding.  The same adjustment is applied to the
92  * times returned from clock_gettime(), because the fraction returned will
93  * always be zero, but on average the actual fraction at the time of the call
94  * should be about .5.
95  */
96 struct rtc_instance {
97 	device_t	clockdev;
98 	int		resolution;
99 	int		flags;
100 	u_int		schedns;
101 	struct timespec resadj;
102 	struct timeout_task
103 			stask;
104 	LIST_ENTRY(rtc_instance)
105 			rtc_entries;
106 };
107 
108 /*
109  * Clocks are updated using a task running on taskqueue_thread.
110  */
111 static void settime_task_func(void *arg, int pending);
112 
113 /*
114  * Registered clocks are kept in a list which is sorted by resolution; the more
115  * accurate clocks get the first shot at providing the time.
116  */
117 LIST_HEAD(rtc_listhead, rtc_instance);
118 static struct rtc_listhead rtc_list = LIST_HEAD_INITIALIZER(rtc_list);
119 static struct sx rtc_list_lock;
120 SX_SYSINIT(rtc_list_lock_init, &rtc_list_lock, "rtc list");
121 
122 /*
123  * On the task thread, invoke the clock_settime() method of the clock.  Do so
124  * holding no locks, so that clock drivers are free to do whatever kind of
125  * locking or sleeping they need to.
126  */
127 static void
128 settime_task_func(void *arg, int pending)
129 {
130 	struct timespec ts;
131 	struct rtc_instance *rtc;
132 
133 	rtc = arg;
134 	if (!(rtc->flags & CLOCKF_SETTIME_NO_TS)) {
135 		getnanotime(&ts);
136 		if (!(rtc->flags & CLOCKF_SETTIME_NO_ADJ)) {
137 			ts.tv_sec -= utc_offset();
138 			timespecadd(&ts, &rtc->resadj);
139 		}
140 	} else {
141 		ts.tv_sec  = 0;
142 		ts.tv_nsec = 0;
143 	}
144 	CLOCK_SETTIME(rtc->clockdev, &ts);
145 }
146 
147 void
148 clock_register_flags(device_t clockdev, long resolution, int flags)
149 {
150 	struct rtc_instance *rtc, *newrtc;
151 
152 	newrtc = malloc(sizeof(*newrtc), M_DEVBUF, M_WAITOK);
153 	newrtc->clockdev = clockdev;
154 	newrtc->resolution = (int)resolution;
155 	newrtc->flags = flags;
156 	newrtc->schedns = 0;
157 	newrtc->resadj.tv_sec  = newrtc->resolution / 2 / 1000000;
158 	newrtc->resadj.tv_nsec = newrtc->resolution / 2 % 1000000 * 1000;
159 	TIMEOUT_TASK_INIT(taskqueue_thread, &newrtc->stask, 0,
160 		    settime_task_func, newrtc);
161 
162 	sx_xlock(&rtc_list_lock);
163 	if (LIST_EMPTY(&rtc_list)) {
164 		LIST_INSERT_HEAD(&rtc_list, newrtc, rtc_entries);
165 	} else {
166 		LIST_FOREACH(rtc, &rtc_list, rtc_entries) {
167 			if (rtc->resolution > newrtc->resolution) {
168 				LIST_INSERT_BEFORE(rtc, newrtc, rtc_entries);
169 				break;
170 			} else if (LIST_NEXT(rtc, rtc_entries) == NULL) {
171 				LIST_INSERT_AFTER(rtc, newrtc, rtc_entries);
172 				break;
173 			}
174 		}
175 	}
176 	sx_xunlock(&rtc_list_lock);
177 
178 	device_printf(clockdev,
179 	    "registered as a time-of-day clock, resolution %d.%6.6ds\n",
180 	    newrtc->resolution / 1000000, newrtc->resolution % 1000000);
181 }
182 
183 void
184 clock_register(device_t dev, long res)
185 {
186 
187 	clock_register_flags(dev, res, 0);
188 }
189 
190 void
191 clock_unregister(device_t clockdev)
192 {
193 	struct rtc_instance *rtc, *tmp;
194 
195 	sx_xlock(&rtc_list_lock);
196 	LIST_FOREACH_SAFE(rtc, &rtc_list, rtc_entries, tmp) {
197 		if (rtc->clockdev == clockdev) {
198 			LIST_REMOVE(rtc, rtc_entries);
199 			break;
200 		}
201 	}
202 	sx_xunlock(&rtc_list_lock);
203 	if (rtc != NULL) {
204 		taskqueue_cancel_timeout(taskqueue_thread, &rtc->stask, NULL);
205 		taskqueue_drain_timeout(taskqueue_thread, &rtc->stask);
206                 free(rtc, M_DEVBUF);
207 	}
208 }
209 
210 void
211 clock_schedule(device_t clockdev, u_int offsetns)
212 {
213 	struct rtc_instance *rtc;
214 
215 	sx_xlock(&rtc_list_lock);
216 	LIST_FOREACH(rtc, &rtc_list, rtc_entries) {
217 		if (rtc->clockdev == clockdev) {
218 			rtc->schedns = offsetns;
219 			break;
220 		}
221 	}
222 	sx_xunlock(&rtc_list_lock);
223 }
224 
225 /*
226  * Initialize the system time.  Must be called from a context which does not
227  * restrict any locking or sleeping that clock drivers may need to do.
228  *
229  * First attempt to get the time from a registered realtime clock.  The clocks
230  * are queried in order of resolution until one provides the time.  If no clock
231  * can provide the current time, use the 'base' time provided by the caller, if
232  * non-zero.  The 'base' time is potentially highly inaccurate, such as the last
233  * known good value of the system clock, or even a filesystem last-updated
234  * timestamp.  It is used to prevent system time from appearing to move
235  * backwards in logs.
236  */
237 void
238 inittodr(time_t base)
239 {
240 	struct timespec ts;
241 	struct rtc_instance *rtc;
242 	int error;
243 
244 	error = ENXIO;
245 	sx_xlock(&rtc_list_lock);
246 	LIST_FOREACH(rtc, &rtc_list, rtc_entries) {
247 		if ((error = CLOCK_GETTIME(rtc->clockdev, &ts)) != 0)
248 			continue;
249 		if (ts.tv_sec < 0 || ts.tv_nsec < 0) {
250 			error = EINVAL;
251 			continue;
252 		}
253 		if (!(rtc->flags & CLOCKF_GETTIME_NO_ADJ)) {
254 			timespecadd(&ts, &rtc->resadj);
255 			ts.tv_sec += utc_offset();
256 		}
257 		if (bootverbose)
258 			device_printf(rtc->clockdev,
259 			    "providing initial system time\n");
260 		break;
261 	}
262 	sx_xunlock(&rtc_list_lock);
263 
264 	/*
265 	 * Do not report errors from each clock; it is expected that some clocks
266 	 * cannot provide results in some situations.  Only report problems when
267 	 * no clocks could provide the time.
268 	 */
269 	if (error != 0) {
270 		switch (error) {
271 		case ENXIO:
272 			printf("Warning: no time-of-day clock registered, ");
273 			break;
274 		case EINVAL:
275 			printf("Warning: bad time from time-of-day clock, ");
276 			break;
277 		default:
278 			printf("Error reading time-of-day clock (%d), ", error);
279 			break;
280 		}
281 		printf("system time will not be set accurately\n");
282 		ts.tv_sec  = (base > 0) ? base : -1;
283 		ts.tv_nsec = 0;
284 	}
285 
286 	if (ts.tv_sec >= 0) {
287 		tc_setclock(&ts);
288 #ifdef FFCLOCK
289 		ffclock_reset_clock(&ts);
290 #endif
291 	}
292 }
293 
294 /*
295  * Write system time back to all registered clocks, unless disabled by admin.
296  * This can be called from a context that restricts locking and/or sleeping; the
297  * actual updating is done asynchronously on a task thread.
298  */
299 void
300 resettodr(void)
301 {
302 	struct timespec now;
303 	struct rtc_instance *rtc;
304 	sbintime_t sbt;
305 	long waitns;
306 
307 	if (disable_rtc_set)
308 		return;
309 
310 	sx_xlock(&rtc_list_lock);
311 	LIST_FOREACH(rtc, &rtc_list, rtc_entries) {
312 		if (rtc->schedns != 0) {
313 			getnanotime(&now);
314 			waitns = rtc->schedns - now.tv_nsec;
315 			if (waitns < 0)
316 				waitns += 1000000000;
317 			sbt = nstosbt(waitns);
318 		} else
319 			sbt = 0;
320 		taskqueue_enqueue_timeout_sbt(taskqueue_thread,
321 		    &rtc->stask, -sbt, 0, C_PREL(31));
322 	}
323 	sx_xunlock(&rtc_list_lock);
324 }
325