1/*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 1982, 1986, 1993
5 *	The Regents of the University of California.  All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 *    may be used to endorse or promote products derived from this software
17 *    without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32#ifndef _SYS_TIME_H_
33#define	_SYS_TIME_H_
34
35#include <sys/_timeval.h>
36#include <sys/types.h>
37#include <sys/timespec.h>
38#include <sys/_clock_id.h>
39
40struct timezone {
41	int	tz_minuteswest;	/* minutes west of Greenwich */
42	int	tz_dsttime;	/* type of dst correction */
43};
44#define	DST_NONE	0	/* not on dst */
45#define	DST_USA		1	/* USA style dst */
46#define	DST_AUST	2	/* Australian style dst */
47#define	DST_WET		3	/* Western European dst */
48#define	DST_MET		4	/* Middle European dst */
49#define	DST_EET		5	/* Eastern European dst */
50#define	DST_CAN		6	/* Canada */
51
52#if __BSD_VISIBLE
53struct bintime {
54	time_t	sec;
55	uint64_t frac;
56};
57
58static __inline void
59bintime_addx(struct bintime *_bt, uint64_t _x)
60{
61	uint64_t _u;
62
63	_u = _bt->frac;
64	_bt->frac += _x;
65	if (_u > _bt->frac)
66		_bt->sec++;
67}
68
69static __inline void
70bintime_add(struct bintime *_bt, const struct bintime *_bt2)
71{
72	uint64_t _u;
73
74	_u = _bt->frac;
75	_bt->frac += _bt2->frac;
76	if (_u > _bt->frac)
77		_bt->sec++;
78	_bt->sec += _bt2->sec;
79}
80
81static __inline void
82bintime_sub(struct bintime *_bt, const struct bintime *_bt2)
83{
84	uint64_t _u;
85
86	_u = _bt->frac;
87	_bt->frac -= _bt2->frac;
88	if (_u < _bt->frac)
89		_bt->sec--;
90	_bt->sec -= _bt2->sec;
91}
92
93static __inline void
94bintime_mul(struct bintime *_bt, u_int _x)
95{
96	uint64_t _p1, _p2;
97
98	_p1 = (_bt->frac & 0xffffffffull) * _x;
99	_p2 = (_bt->frac >> 32) * _x + (_p1 >> 32);
100	_bt->sec *= _x;
101	_bt->sec += (_p2 >> 32);
102	_bt->frac = (_p2 << 32) | (_p1 & 0xffffffffull);
103}
104
105static __inline void
106bintime_shift(struct bintime *_bt, int _exp)
107{
108
109	if (_exp > 0) {
110		_bt->sec <<= _exp;
111		_bt->sec |= _bt->frac >> (64 - _exp);
112		_bt->frac <<= _exp;
113	} else if (_exp < 0) {
114		_bt->frac >>= -_exp;
115		_bt->frac |= (uint64_t)_bt->sec << (64 + _exp);
116		_bt->sec >>= -_exp;
117	}
118}
119
120#define	bintime_clear(a)	((a)->sec = (a)->frac = 0)
121#define	bintime_isset(a)	((a)->sec || (a)->frac)
122#define	bintime_cmp(a, b, cmp)						\
123	(((a)->sec == (b)->sec) ?					\
124	    ((a)->frac cmp (b)->frac) :					\
125	    ((a)->sec cmp (b)->sec))
126
127#define	SBT_1S	((sbintime_t)1 << 32)
128#define	SBT_1M	(SBT_1S * 60)
129#define	SBT_1MS	(SBT_1S / 1000)
130#define	SBT_1US	(SBT_1S / 1000000)
131#define	SBT_1NS	(SBT_1S / 1000000000) /* beware rounding, see nstosbt() */
132#define	SBT_MAX	0x7fffffffffffffffLL
133
134static __inline int
135sbintime_getsec(sbintime_t _sbt)
136{
137
138	return (_sbt >> 32);
139}
140
141static __inline sbintime_t
142bttosbt(const struct bintime _bt)
143{
144
145	return (((sbintime_t)_bt.sec << 32) + (_bt.frac >> 32));
146}
147
148static __inline struct bintime
149sbttobt(sbintime_t _sbt)
150{
151	struct bintime _bt;
152
153	_bt.sec = _sbt >> 32;
154	_bt.frac = _sbt << 32;
155	return (_bt);
156}
157
158/*
159 * Scaling functions for signed and unsigned 64-bit time using any
160 * 32-bit fraction:
161 */
162
163static __inline int64_t
164__stime64_scale32_ceil(int64_t x, int32_t factor, int32_t divisor)
165{
166	const int64_t rem = x % divisor;
167
168	return (x / divisor * factor + (rem * factor + divisor - 1) / divisor);
169}
170
171static __inline int64_t
172__stime64_scale32_floor(int64_t x, int32_t factor, int32_t divisor)
173{
174	const int64_t rem = x % divisor;
175
176	return (x / divisor * factor + (rem * factor) / divisor);
177}
178
179static __inline uint64_t
180__utime64_scale32_ceil(uint64_t x, uint32_t factor, uint32_t divisor)
181{
182	const uint64_t rem = x % divisor;
183
184	return (x / divisor * factor + (rem * factor + divisor - 1) / divisor);
185}
186
187static __inline uint64_t
188__utime64_scale32_floor(uint64_t x, uint32_t factor, uint32_t divisor)
189{
190	const uint64_t rem = x % divisor;
191
192	return (x / divisor * factor + (rem * factor) / divisor);
193}
194
195/*
196 * This function finds the common divisor between the two arguments,
197 * in powers of two. Use a macro, so the compiler will output a
198 * warning if the value overflows!
199 *
200 * Detailed description:
201 *
202 * Create a variable with 1's at the positions of the leading 0's
203 * starting at the least significant bit, producing 0 if none (e.g.,
204 * 01011000 -> 0000 0111). Then these two variables are bitwise AND'ed
205 * together, to produce the greatest common power of two minus one. In
206 * the end add one to flip the value to the actual power of two (e.g.,
207 * 0000 0111 + 1 -> 0000 1000).
208 */
209#define	__common_powers_of_two(a, b) \
210	((~(a) & ((a) - 1) & ~(b) & ((b) - 1)) + 1)
211
212/*
213 * Scaling functions for signed and unsigned 64-bit time assuming
214 * reducable 64-bit fractions to 32-bit fractions:
215 */
216
217static __inline int64_t
218__stime64_scale64_ceil(int64_t x, int64_t factor, int64_t divisor)
219{
220	const int64_t gcd = __common_powers_of_two(factor, divisor);
221
222	return (__stime64_scale32_ceil(x, factor / gcd, divisor / gcd));
223}
224
225static __inline int64_t
226__stime64_scale64_floor(int64_t x, int64_t factor, int64_t divisor)
227{
228	const int64_t gcd = __common_powers_of_two(factor, divisor);
229
230	return (__stime64_scale32_floor(x, factor / gcd, divisor / gcd));
231}
232
233static __inline uint64_t
234__utime64_scale64_ceil(uint64_t x, uint64_t factor, uint64_t divisor)
235{
236	const uint64_t gcd = __common_powers_of_two(factor, divisor);
237
238	return (__utime64_scale32_ceil(x, factor / gcd, divisor / gcd));
239}
240
241static __inline uint64_t
242__utime64_scale64_floor(uint64_t x, uint64_t factor, uint64_t divisor)
243{
244	const uint64_t gcd = __common_powers_of_two(factor, divisor);
245
246	return (__utime64_scale32_floor(x, factor / gcd, divisor / gcd));
247}
248
249/*
250 * Decimal<->sbt conversions. Multiplying or dividing by SBT_1NS
251 * results in large roundoff errors which sbttons() and nstosbt()
252 * avoid. Millisecond and microsecond functions are also provided for
253 * completeness.
254 *
255 * When converting from sbt to another unit, the result is always
256 * rounded down. When converting back to sbt the result is always
257 * rounded up. This gives the property that sbttoX(Xtosbt(y)) == y .
258 *
259 * The conversion functions can also handle negative values.
260 */
261#define	SBT_DECLARE_CONVERSION_PAIR(name, units_per_second)	\
262static __inline int64_t \
263sbtto##name(sbintime_t sbt) \
264{ \
265	return (__stime64_scale64_floor(sbt, units_per_second, SBT_1S)); \
266} \
267static __inline sbintime_t \
268name##tosbt(int64_t name) \
269{ \
270	return (__stime64_scale64_ceil(name, SBT_1S, units_per_second)); \
271}
272
273SBT_DECLARE_CONVERSION_PAIR(ns, 1000000000)
274SBT_DECLARE_CONVERSION_PAIR(us, 1000000)
275SBT_DECLARE_CONVERSION_PAIR(ms, 1000)
276
277/*-
278 * Background information:
279 *
280 * When converting between timestamps on parallel timescales of differing
281 * resolutions it is historical and scientific practice to round down rather
282 * than doing 4/5 rounding.
283 *
284 *   The date changes at midnight, not at noon.
285 *
286 *   Even at 15:59:59.999999999 it's not four'o'clock.
287 *
288 *   time_second ticks after N.999999999 not after N.4999999999
289 */
290
291static __inline void
292bintime2timespec(const struct bintime *_bt, struct timespec *_ts)
293{
294
295	_ts->tv_sec = _bt->sec;
296	_ts->tv_nsec = __utime64_scale64_floor(
297	    _bt->frac, 1000000000, 1ULL << 32) >> 32;
298}
299
300static __inline uint64_t
301bintime2ns(const struct bintime *_bt)
302{
303	uint64_t ret;
304
305	ret = (uint64_t)(_bt->sec) * (uint64_t)1000000000;
306	ret += __utime64_scale64_floor(
307	    _bt->frac, 1000000000, 1ULL << 32) >> 32;
308	return (ret);
309}
310
311static __inline void
312timespec2bintime(const struct timespec *_ts, struct bintime *_bt)
313{
314
315	_bt->sec = _ts->tv_sec;
316	_bt->frac = __utime64_scale64_floor(
317	    (uint64_t)_ts->tv_nsec << 32, 1ULL << 32, 1000000000);
318}
319
320static __inline void
321bintime2timeval(const struct bintime *_bt, struct timeval *_tv)
322{
323
324	_tv->tv_sec = _bt->sec;
325	_tv->tv_usec = __utime64_scale64_floor(
326	    _bt->frac, 1000000, 1ULL << 32) >> 32;
327}
328
329static __inline void
330timeval2bintime(const struct timeval *_tv, struct bintime *_bt)
331{
332
333	_bt->sec = _tv->tv_sec;
334	_bt->frac = __utime64_scale64_floor(
335	    (uint64_t)_tv->tv_usec << 32, 1ULL << 32, 1000000);
336}
337
338static __inline struct timespec
339sbttots(sbintime_t _sbt)
340{
341	struct timespec _ts;
342
343	_ts.tv_sec = _sbt >> 32;
344	_ts.tv_nsec = sbttons((uint32_t)_sbt);
345	return (_ts);
346}
347
348static __inline sbintime_t
349tstosbt(struct timespec _ts)
350{
351
352	return (((sbintime_t)_ts.tv_sec << 32) + nstosbt(_ts.tv_nsec));
353}
354
355static __inline struct timeval
356sbttotv(sbintime_t _sbt)
357{
358	struct timeval _tv;
359
360	_tv.tv_sec = _sbt >> 32;
361	_tv.tv_usec = sbttous((uint32_t)_sbt);
362	return (_tv);
363}
364
365static __inline sbintime_t
366tvtosbt(struct timeval _tv)
367{
368
369	return (((sbintime_t)_tv.tv_sec << 32) + ustosbt(_tv.tv_usec));
370}
371#endif /* __BSD_VISIBLE */
372
373#ifdef _KERNEL
374/*
375 * Simple macros to convert ticks to milliseconds
376 * or microseconds and vice-versa. The answer
377 * will always be at least 1. Note the return
378 * value is a uint32_t however we step up the
379 * operations to 64 bit to avoid any overflow/underflow
380 * problems.
381 */
382#define TICKS_2_MSEC(t) max(1, (uint32_t)(hz == 1000) ? \
383	  (t) : (((uint64_t)(t) * (uint64_t)1000)/(uint64_t)hz))
384#define TICKS_2_USEC(t) max(1, (uint32_t)(hz == 1000) ? \
385	  ((t) * 1000) : (((uint64_t)(t) * (uint64_t)1000000)/(uint64_t)hz))
386#define MSEC_2_TICKS(m) max(1, (uint32_t)((hz == 1000) ? \
387	  (m) : ((uint64_t)(m) * (uint64_t)hz)/(uint64_t)1000))
388#define USEC_2_TICKS(u) max(1, (uint32_t)((hz == 1000) ? \
389	 ((u) / 1000) : ((uint64_t)(u) * (uint64_t)hz)/(uint64_t)1000000))
390
391#endif
392/* Operations on timespecs */
393#define	timespecclear(tvp)	((tvp)->tv_sec = (tvp)->tv_nsec = 0)
394#define	timespecisset(tvp)	((tvp)->tv_sec || (tvp)->tv_nsec)
395#define	timespeccmp(tvp, uvp, cmp)					\
396	(((tvp)->tv_sec == (uvp)->tv_sec) ?				\
397	    ((tvp)->tv_nsec cmp (uvp)->tv_nsec) :			\
398	    ((tvp)->tv_sec cmp (uvp)->tv_sec))
399
400#define	timespecadd(tsp, usp, vsp)					\
401	do {								\
402		(vsp)->tv_sec = (tsp)->tv_sec + (usp)->tv_sec;		\
403		(vsp)->tv_nsec = (tsp)->tv_nsec + (usp)->tv_nsec;	\
404		if ((vsp)->tv_nsec >= 1000000000L) {			\
405			(vsp)->tv_sec++;				\
406			(vsp)->tv_nsec -= 1000000000L;			\
407		}							\
408	} while (0)
409#define	timespecsub(tsp, usp, vsp)					\
410	do {								\
411		(vsp)->tv_sec = (tsp)->tv_sec - (usp)->tv_sec;		\
412		(vsp)->tv_nsec = (tsp)->tv_nsec - (usp)->tv_nsec;	\
413		if ((vsp)->tv_nsec < 0) {				\
414			(vsp)->tv_sec--;				\
415			(vsp)->tv_nsec += 1000000000L;			\
416		}							\
417	} while (0)
418#define	timespecvalid_interval(tsp)	((tsp)->tv_sec >= 0 &&		\
419	    (tsp)->tv_nsec >= 0 && (tsp)->tv_nsec < 1000000000L)
420
421#ifdef _KERNEL
422
423/* Operations on timevals. */
424
425#define	timevalclear(tvp)		((tvp)->tv_sec = (tvp)->tv_usec = 0)
426#define	timevalisset(tvp)		((tvp)->tv_sec || (tvp)->tv_usec)
427#define	timevalcmp(tvp, uvp, cmp)					\
428	(((tvp)->tv_sec == (uvp)->tv_sec) ?				\
429	    ((tvp)->tv_usec cmp (uvp)->tv_usec) :			\
430	    ((tvp)->tv_sec cmp (uvp)->tv_sec))
431
432/* timevaladd and timevalsub are not inlined */
433
434#endif /* _KERNEL */
435
436#ifndef _KERNEL			/* NetBSD/OpenBSD compatible interfaces */
437
438#define	timerclear(tvp)		((tvp)->tv_sec = (tvp)->tv_usec = 0)
439#define	timerisset(tvp)		((tvp)->tv_sec || (tvp)->tv_usec)
440#define	timercmp(tvp, uvp, cmp)					\
441	(((tvp)->tv_sec == (uvp)->tv_sec) ?				\
442	    ((tvp)->tv_usec cmp (uvp)->tv_usec) :			\
443	    ((tvp)->tv_sec cmp (uvp)->tv_sec))
444#define	timeradd(tvp, uvp, vvp)						\
445	do {								\
446		(vvp)->tv_sec = (tvp)->tv_sec + (uvp)->tv_sec;		\
447		(vvp)->tv_usec = (tvp)->tv_usec + (uvp)->tv_usec;	\
448		if ((vvp)->tv_usec >= 1000000) {			\
449			(vvp)->tv_sec++;				\
450			(vvp)->tv_usec -= 1000000;			\
451		}							\
452	} while (0)
453#define	timersub(tvp, uvp, vvp)						\
454	do {								\
455		(vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec;		\
456		(vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec;	\
457		if ((vvp)->tv_usec < 0) {				\
458			(vvp)->tv_sec--;				\
459			(vvp)->tv_usec += 1000000;			\
460		}							\
461	} while (0)
462#endif
463
464/*
465 * Names of the interval timers, and structure
466 * defining a timer setting.
467 */
468#define	ITIMER_REAL	0
469#define	ITIMER_VIRTUAL	1
470#define	ITIMER_PROF	2
471
472struct itimerval {
473	struct	timeval it_interval;	/* timer interval */
474	struct	timeval it_value;	/* current value */
475};
476
477/*
478 * Getkerninfo clock information structure
479 */
480struct clockinfo {
481	int	hz;		/* clock frequency */
482	int	tick;		/* micro-seconds per hz tick */
483	int	spare;
484	int	stathz;		/* statistics clock frequency */
485	int	profhz;		/* profiling clock frequency */
486};
487
488#if __BSD_VISIBLE
489#define	CPUCLOCK_WHICH_PID	0
490#define	CPUCLOCK_WHICH_TID	1
491#endif
492
493#if defined(_KERNEL) || defined(_STANDALONE)
494
495/*
496 * Kernel to clock driver interface.
497 */
498void	inittodr(time_t base);
499void	resettodr(void);
500
501extern volatile time_t	time_second;
502extern volatile time_t	time_uptime;
503extern struct bintime tc_tick_bt;
504extern sbintime_t tc_tick_sbt;
505extern time_t tick_seconds_max;
506extern struct bintime tick_bt;
507extern sbintime_t tick_sbt;
508extern int tc_precexp;
509extern int tc_timepercentage;
510extern struct bintime bt_timethreshold;
511extern struct bintime bt_tickthreshold;
512extern sbintime_t sbt_timethreshold;
513extern sbintime_t sbt_tickthreshold;
514
515extern volatile int rtc_generation;
516
517/*
518 * Functions for looking at our clock: [get]{bin,nano,micro}[up]time()
519 *
520 * Functions without the "get" prefix returns the best timestamp
521 * we can produce in the given format.
522 *
523 * "bin"   == struct bintime  == seconds + 64 bit fraction of seconds.
524 * "nano"  == struct timespec == seconds + nanoseconds.
525 * "micro" == struct timeval  == seconds + microseconds.
526 *
527 * Functions containing "up" returns time relative to boot and
528 * should be used for calculating time intervals.
529 *
530 * Functions without "up" returns UTC time.
531 *
532 * Functions with the "get" prefix returns a less precise result
533 * much faster than the functions without "get" prefix and should
534 * be used where a precision of 1/hz seconds is acceptable or where
535 * performance is priority. (NB: "precision", _not_ "resolution" !)
536 */
537
538void	binuptime(struct bintime *bt);
539void	nanouptime(struct timespec *tsp);
540void	microuptime(struct timeval *tvp);
541
542static __inline sbintime_t
543sbinuptime(void)
544{
545	struct bintime _bt;
546
547	binuptime(&_bt);
548	return (bttosbt(_bt));
549}
550
551void	bintime(struct bintime *bt);
552void	nanotime(struct timespec *tsp);
553void	microtime(struct timeval *tvp);
554
555void	getbinuptime(struct bintime *bt);
556void	getnanouptime(struct timespec *tsp);
557void	getmicrouptime(struct timeval *tvp);
558
559static __inline sbintime_t
560getsbinuptime(void)
561{
562	struct bintime _bt;
563
564	getbinuptime(&_bt);
565	return (bttosbt(_bt));
566}
567
568void	getbintime(struct bintime *bt);
569void	getnanotime(struct timespec *tsp);
570void	getmicrotime(struct timeval *tvp);
571
572void	getboottime(struct timeval *boottime);
573void	getboottimebin(struct bintime *boottimebin);
574
575/* Other functions */
576int	itimerdecr(struct itimerval *itp, int usec);
577int	itimerfix(struct timeval *tv);
578int	eventratecheck(struct timeval *, int *, int);
579#define	ppsratecheck(t, c, m) eventratecheck(t, c, m)
580int	ratecheck(struct timeval *, const struct timeval *);
581void	timevaladd(struct timeval *t1, const struct timeval *t2);
582void	timevalsub(struct timeval *t1, const struct timeval *t2);
583int	tvtohz(struct timeval *tv);
584
585/*
586 * The following HZ limits allow the tvtohz() function
587 * to only use integer computations.
588 */
589#define	HZ_MAXIMUM (INT_MAX / (1000000 >> 6)) /* 137kHz */
590#define	HZ_MINIMUM 8 /* hz */
591
592#define	TC_DEFAULTPERC		5
593
594#define	BT2FREQ(bt)                                                     \
595	(((uint64_t)0x8000000000000000 + ((bt)->frac >> 2)) /           \
596	    ((bt)->frac >> 1))
597
598#define	SBT2FREQ(sbt)	((SBT_1S + ((sbt) >> 1)) / (sbt))
599
600#define	FREQ2BT(freq, bt)                                               \
601{									\
602	(bt)->sec = 0;                                                  \
603	(bt)->frac = ((uint64_t)0x8000000000000000  / (freq)) << 1;     \
604}
605
606#define	TIMESEL(sbt, sbt2)						\
607	(((sbt2) >= sbt_timethreshold) ?				\
608	    ((*(sbt) = getsbinuptime()), 1) : ((*(sbt) = sbinuptime()), 0))
609
610#else /* !_KERNEL && !_STANDALONE */
611#include <time.h>
612
613#include <sys/cdefs.h>
614#include <sys/select.h>
615
616__BEGIN_DECLS
617int	setitimer(int, const struct itimerval *, struct itimerval *);
618int	utimes(const char *, const struct timeval *);
619
620#if __BSD_VISIBLE
621int	adjtime(const struct timeval *, struct timeval *);
622int	clock_getcpuclockid2(id_t, int, clockid_t *);
623int	futimes(int, const struct timeval *);
624int	futimesat(int, const char *, const struct timeval [2]);
625int	lutimes(const char *, const struct timeval *);
626int	settimeofday(const struct timeval *, const struct timezone *);
627#endif
628
629#if __XSI_VISIBLE
630int	getitimer(int, struct itimerval *);
631int	gettimeofday(struct timeval *, struct timezone *);
632#endif
633
634__END_DECLS
635
636#endif /* !_KERNEL */
637
638#endif /* !_SYS_TIME_H_ */
639