subr_time_arith.c revision 1.3 1 /* $NetBSD: subr_time_arith.c,v 1.3 2025/04/01 23:14:23 riastradh Exp $ */
2
3 /*-
4 * Copyright (c) 2000, 2004, 2005, 2007, 2008, 2009, 2020
5 * The NetBSD Foundation, Inc.
6 * All rights reserved.
7 *
8 * This code is derived from software contributed to The NetBSD Foundation
9 * by Christopher G. Demetriou, by Andrew Doran, and by Jason R. Thorpe.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
31 */
32
33 /*
34 * Copyright (c) 1982, 1986, 1989, 1993
35 * The Regents of the University of California. All rights reserved.
36 *
37 * Redistribution and use in source and binary forms, with or without
38 * modification, are permitted provided that the following conditions
39 * are met:
40 * 1. Redistributions of source code must retain the above copyright
41 * notice, this list of conditions and the following disclaimer.
42 * 2. Redistributions in binary form must reproduce the above copyright
43 * notice, this list of conditions and the following disclaimer in the
44 * documentation and/or other materials provided with the distribution.
45 * 3. Neither the name of the University nor the names of its contributors
46 * may be used to endorse or promote products derived from this software
47 * without specific prior written permission.
48 *
49 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
50 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
52 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
53 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
54 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
55 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
57 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
58 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
59 * SUCH DAMAGE.
60 *
61 * @(#)kern_clock.c 8.5 (Berkeley) 1/21/94
62 * @(#)kern_time.c 8.4 (Berkeley) 5/26/95
63 */
64
65 #include <sys/cdefs.h>
66 __KERNEL_RCSID(0, "$NetBSD: subr_time_arith.c,v 1.3 2025/04/01 23:14:23 riastradh Exp $");
67
68 #include <sys/types.h>
69
70 #include <sys/errno.h>
71 #include <sys/time.h>
72 #include <sys/timearith.h>
73
74 #if defined(_KERNEL)
75
76 #include <sys/kernel.h>
77 #include <sys/systm.h>
78
79 #include <machine/limits.h>
80
81 #elif defined(_TIME_TESTING)
82
83 #include <assert.h>
84 #include <limits.h>
85 #include <stdbool.h>
86
87 extern int hz;
88 extern int tick;
89
90 #define KASSERT assert
91 #define MIN(X, Y) ((X) < (Y) ? (X) : (Y))
92
93 #endif
94
95 /*
96 * Compute number of ticks in the specified amount of time.
97 */
98 int
99 tvtohz(const struct timeval *tv)
100 {
101 unsigned long ticks;
102 long sec, usec;
103
104 /*
105 * If the number of usecs in the whole seconds part of the time
106 * difference fits in a long, then the total number of usecs will
107 * fit in an unsigned long. Compute the total and convert it to
108 * ticks, rounding up and adding 1 to allow for the current tick
109 * to expire. Rounding also depends on unsigned long arithmetic
110 * to avoid overflow.
111 *
112 * Otherwise, if the number of ticks in the whole seconds part of
113 * the time difference fits in a long, then convert the parts to
114 * ticks separately and add, using similar rounding methods and
115 * overflow avoidance. This method would work in the previous
116 * case, but it is slightly slower and assumes that hz is integral.
117 *
118 * Otherwise, round the time difference down to the maximum
119 * representable value.
120 *
121 * If ints are 32-bit, then the maximum value for any timeout in
122 * 10ms ticks is 248 days.
123 */
124 sec = tv->tv_sec;
125 usec = tv->tv_usec;
126
127 KASSERT(usec >= 0);
128 KASSERT(usec < 1000000);
129
130 /* catch overflows in conversion time_t->int */
131 if (tv->tv_sec > INT_MAX)
132 return INT_MAX;
133 if (tv->tv_sec < 0)
134 return 0;
135
136 if (sec < 0 || (sec == 0 && usec == 0)) {
137 /*
138 * Would expire now or in the past. Return 0 ticks.
139 * This is different from the legacy tvhzto() interface,
140 * and callers need to check for it.
141 */
142 ticks = 0;
143 } else if (sec <= (LONG_MAX / 1000000))
144 ticks = (((sec * 1000000) + (unsigned long)usec + (tick - 1))
145 / tick) + 1;
146 else if (sec <= (LONG_MAX / hz))
147 ticks = (sec * hz) +
148 (((unsigned long)usec + (tick - 1)) / tick) + 1;
149 else
150 ticks = LONG_MAX;
151
152 if (ticks > INT_MAX)
153 ticks = INT_MAX;
154
155 return ((int)ticks);
156 }
157
158 /*
159 * Check that a proposed value to load into the .it_value or
160 * .it_interval part of an interval timer is acceptable, and
161 * fix it to have at least minimal value (i.e. if it is less
162 * than the resolution of the clock, round it up.). We don't
163 * timeout the 0,0 value because this means to disable the
164 * timer or the interval.
165 */
166 int
167 itimerfix(struct timeval *tv)
168 {
169
170 if (tv->tv_usec < 0 || tv->tv_usec >= 1000000)
171 return EINVAL;
172 if (tv->tv_sec < 0)
173 return ETIMEDOUT;
174 if (tv->tv_sec == 0 && tv->tv_usec != 0 && tv->tv_usec < tick)
175 tv->tv_usec = tick;
176 return 0;
177 }
178
179 int
180 itimespecfix(struct timespec *ts)
181 {
182
183 if (ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000)
184 return EINVAL;
185 if (ts->tv_sec < 0)
186 return ETIMEDOUT;
187 if (ts->tv_sec == 0 && ts->tv_nsec != 0 && ts->tv_nsec < tick * 1000)
188 ts->tv_nsec = tick * 1000;
189 return 0;
190 }
191
192 /*
193 * timespecaddok(tsp, usp)
194 *
195 * True if tsp + usp can be computed without overflow, i.e., if it
196 * is OK to do timespecadd(tsp, usp, ...).
197 */
198 bool
199 timespecaddok(const struct timespec *tsp, const struct timespec *usp)
200 {
201 enum { TIME_MIN = __type_min(time_t), TIME_MAX = __type_max(time_t) };
202 time_t a = tsp->tv_sec;
203 time_t b = usp->tv_sec;
204 bool carry;
205
206 /*
207 * Caller is responsible for guaranteeing valid timespec
208 * inputs. Any user-controlled inputs must be validated or
209 * adjusted.
210 */
211 KASSERT(tsp->tv_nsec >= 0);
212 KASSERT(usp->tv_nsec >= 0);
213 KASSERT(tsp->tv_nsec < 1000000000L);
214 KASSERT(usp->tv_nsec < 1000000000L);
215 __CTASSERT(1000000000L <= __type_max(long) - 1000000000L);
216
217 /*
218 * Fail if a + b + carry overflows TIME_MAX, or if a + b
219 * overflows TIME_MIN because timespecadd adds the carry after
220 * computing a + b.
221 *
222 * Break it into two mutually exclusive and exhaustive cases:
223 * I. a >= 0
224 * II. a < 0
225 */
226 carry = (tsp->tv_nsec + usp->tv_nsec >= 1000000000L);
227 if (a >= 0) {
228 /*
229 * Case I: a >= 0. If b < 0, then b + 1 <= 0, so
230 *
231 * a + b + 1 <= a + 0 <= TIME_MAX,
232 *
233 * and
234 *
235 * a + b >= 0 + b = b >= TIME_MIN,
236 *
237 * so this can't overflow.
238 *
239 * If b >= 0, then a + b + carry >= a + b >= 0, so
240 * negative results and thus results below TIME_MIN are
241 * impossible; we need only avoid
242 *
243 * a + b + carry > TIME_MAX,
244 *
245 * which we will do by rejecting if
246 *
247 * b > TIME_MAX - a - carry,
248 *
249 * which in turn is incidentally always false if b < 0
250 * so we don't need extra logic to discriminate on the
251 * b >= 0 and b < 0 cases.
252 *
253 * Since 0 <= a <= TIME_MAX, we know
254 *
255 * 0 <= TIME_MAX - a <= TIME_MAX,
256 *
257 * and hence
258 *
259 * -1 <= TIME_MAX - a - 1 < TIME_MAX.
260 *
261 * So we can compute TIME_MAX - a - carry (i.e., either
262 * TIME_MAX - a or TIME_MAX - a - 1) safely without
263 * overflow.
264 */
265 if (b > TIME_MAX - a - carry)
266 return false;
267 } else {
268 /*
269 * Case II: a < 0. If b >= 0, then since a + 1 <= 0,
270 * we have
271 *
272 * a + b + 1 <= b <= TIME_MAX,
273 *
274 * and
275 *
276 * a + b >= a >= TIME_MIN,
277 *
278 * so this can't overflow.
279 *
280 * If b < 0, then the intermediate a + b is negative
281 * and the outcome a + b + 1 is nonpositive, so we need
282 * only avoid
283 *
284 * a + b < TIME_MIN,
285 *
286 * which we will do by rejecting if
287 *
288 * a < TIME_MIN - b.
289 *
290 * (Reminder: The carry is added afterward in
291 * timespecadd, so to avoid overflow it is not enough
292 * to merely reject a + b + carry < TIME_MIN.)
293 *
294 * It is safe to compute the difference TIME_MIN - b
295 * because b is negative, so the result lies in
296 * (TIME_MIN, 0].
297 */
298 if (b < 0 && a < TIME_MIN - b)
299 return false;
300 }
301
302 return true;
303 }
304
305 /*
306 * timespecsubok(tsp, usp)
307 *
308 * True if tsp - usp can be computed without overflow, i.e., if it
309 * is OK to do timespecsub(tsp, usp, ...).
310 */
311 bool
312 timespecsubok(const struct timespec *tsp, const struct timespec *usp)
313 {
314 enum { TIME_MIN = __type_min(time_t), TIME_MAX = __type_max(time_t) };
315 time_t a = tsp->tv_sec, b = usp->tv_sec;
316 bool borrow;
317
318 /*
319 * Caller is responsible for guaranteeing valid timespec
320 * inputs. Any user-controlled inputs must be validated or
321 * adjusted.
322 */
323 KASSERT(tsp->tv_nsec >= 0);
324 KASSERT(usp->tv_nsec >= 0);
325 KASSERT(tsp->tv_nsec < 1000000000L);
326 KASSERT(usp->tv_nsec < 1000000000L);
327 __CTASSERT(1000000000L <= __type_max(long) - 1000000000L);
328
329 /*
330 * Fail if a - b - borrow overflows TIME_MIN, or if a - b
331 * overflows TIME_MAX because timespecsub subtracts the borrow
332 * after computing a - b.
333 *
334 * Break it into two mutually exclusive and exhaustive cases:
335 * I. a < 0
336 * II. a >= 0
337 */
338 borrow = (tsp->tv_nsec - usp->tv_nsec < 0);
339 if (a < 0) {
340 /*
341 * Case I: a < 0. If b < 0, then -b - 1 >= 0, so
342 *
343 * a - b - 1 >= a + 0 >= TIME_MIN,
344 *
345 * and, since a <= -1, provided that TIME_MIN <=
346 * -TIME_MAX - 1 so that TIME_MAX <= -TIME_MIN - 1 (in
347 * fact, equality holds, under the assumption of
348 * two's-complement arithmetic),
349 *
350 * a - b <= -1 - b = -b - 1 <= TIME_MAX,
351 *
352 * so this can't overflow.
353 */
354 __CTASSERT(TIME_MIN <= -TIME_MAX - 1);
355
356 /*
357 * If b >= 0, then a - b - borrow <= a - b < 0, so
358 * positive results and thus results above TIME_MAX are
359 * impossible; we need only avoid
360 *
361 * a - b - borrow < TIME_MIN,
362 *
363 * which we will do by rejecting if
364 *
365 * a < TIME_MIN + b + borrow.
366 *
367 * The right-hand side is safe to evaluate for any
368 * values of b and borrow as long as TIME_MIN +
369 * TIME_MAX + 1 <= TIME_MAX, i.e., TIME_MIN <= -1.
370 * (Note: If time_t were unsigned, this would fail!)
371 *
372 * Note: Unlike Case I in timespecaddok, this criterion
373 * does not work for b < 0, nor can the roles of a and
374 * b in the inequality be reversed (e.g., -b < TIME_MIN
375 * - a + borrow) without extra cases like checking for
376 * b = TEST_MIN.
377 */
378 __CTASSERT(TIME_MIN < -1);
379 if (b >= 0 && a < TIME_MIN + b + borrow)
380 return false;
381 } else {
382 /*
383 * Case II: a >= 0. If b >= 0, then
384 *
385 * a - b <= a <= TIME_MAX,
386 *
387 * and, provided TIME_MIN <= -TIME_MAX - 1 (in fact,
388 * equality holds, under the assumption of
389 * two's-complement arithmetic)
390 *
391 * a - b - 1 >= -b - 1 >= -TIME_MAX - 1 >= TIME_MIN,
392 *
393 * so this can't overflow.
394 */
395 __CTASSERT(TIME_MIN <= -TIME_MAX - 1);
396
397 /*
398 * If b < 0, then a - b >= a >= 0, so negative results
399 * and thus results below TIME_MIN are impossible; we
400 * need only avoid
401 *
402 * a - b > TIME_MAX,
403 *
404 * which we will do by rejecting if
405 *
406 * a > TIME_MAX + b.
407 *
408 * (Reminder: The borrow is subtracted afterward in
409 * timespecsub, so to avoid overflow it is not enough
410 * to merely reject a - b - borrow > TIME_MAX.)
411 *
412 * It is safe to compute the sum TIME_MAX + b because b
413 * is negative, so the result lies in [0, TIME_MAX).
414 */
415 if (b < 0 && a > TIME_MAX + b)
416 return false;
417 }
418
419 return true;
420 }
421
422 static bool
423 timespec2nsok(const struct timespec *ts)
424 {
425
426 return ts->tv_sec < INT64_MAX/1000000000 ||
427 (ts->tv_sec == INT64_MAX/1000000000 &&
428 ts->tv_nsec <= INT64_MAX - (INT64_MAX/1000000000)*1000000000);
429 }
430
431 /*
432 * itimer_transition(it, now, next, &overruns)
433 *
434 * Given:
435 *
436 * - it: the current state of an itimer (it_value = last expiry
437 * time, it_interval = periodic rescheduling interval), and
438 *
439 * - now: the current time on the itimer's clock;
440 *
441 * compute:
442 *
443 * - next: the next time the itimer should be scheduled for, and
444 * - overruns: the number of overruns if we're firing late.
445 *
446 * XXX This should maybe also say whether the itimer should expire
447 * at all.
448 */
449 void
450 itimer_transition(const struct itimerspec *restrict it,
451 const struct timespec *restrict now,
452 struct timespec *restrict next,
453 int *restrict overrunsp)
454 {
455 int64_t last_val, next_val, interval, remainder, now_ns;
456 int backwards;
457
458 /*
459 * Zero the outputs so we can test assertions in userland
460 * without undefined behaviour.
461 */
462 timespecclear(next);
463 *overrunsp = 0;
464
465 /*
466 * Paranoia: Caller should guarantee this.
467 */
468 if (!timespecisset(&it->it_interval)) {
469 timespecclear(next);
470 return;
471 }
472
473 /* Did the clock wind backwards? */
474 backwards = (timespeccmp(&it->it_value, now, >));
475
476 /* Valid value and interval guaranteed by itimerfix. */
477 KASSERT(it->it_value.tv_sec >= 0);
478 KASSERT(it->it_value.tv_nsec < 1000000000);
479 KASSERT(it->it_interval.tv_sec >= 0);
480 KASSERT(it->it_interval.tv_nsec < 1000000000);
481
482 /* Nonnegative interval guaranteed by itimerfix. */
483 KASSERT(it->it_interval.tv_sec >= 0);
484 KASSERT(it->it_interval.tv_nsec >= 0);
485
486 /* Handle the easy case of non-overflown timers first. */
487 if (__predict_true(!backwards)) {
488 if (__predict_false(!timespecaddok(&it->it_value,
489 &it->it_interval)))
490 goto overflow;
491 timespecadd(&it->it_value, &it->it_interval, next);
492 if (__predict_true(timespeccmp(now, next, <)))
493 return;
494 }
495
496 /*
497 * If we can't represent the input as a number of nanoseconds,
498 * bail. This is good up to the year 2262, if we start
499 * counting from 1970 (2^63 nanoseconds ~ 292 years).
500 */
501 if (__predict_false(!timespec2nsok(now)) ||
502 __predict_false(!timespec2nsok(&it->it_value)) ||
503 __predict_false(!timespec2nsok(&it->it_interval)))
504 goto overflow;
505
506 now_ns = timespec2ns(now);
507 last_val = timespec2ns(&it->it_value);
508 interval = timespec2ns(&it->it_interval);
509
510 KASSERT(now_ns >= 0);
511 KASSERT(last_val >= 0);
512 KASSERT(interval >= 0);
513
514 /*
515 * now [backwards] overruns now [forwards]
516 * | v v v |
517 * |--+----+-*--x----+----+----|----+----+----+--*-x----+-->
518 * \/ | \/
519 * remainder last_val remainder
520 * (zero or negative) (zero or positive)
521 *
522 * Set next_val to last_value + k*interval for some k.
523 *
524 * The interval is always positive, and division in C
525 * truncates, so dividing a positive duration by the interval
526 * always gives zero or a positive remainder, and dividing a
527 * negative duration by the interval always gives zero or a
528 * negative remainder. Hence:
529 *
530 * - If now_ns < last_val -- which happens iff backwards, i.e.,
531 * the clock was wound backwards -- then remainder is zero or
532 * negative, so subtracting it stays in place or moves
533 * forward in time, and thus this finds the _earliest_ value
534 * that is not earlier than now_ns. We will advance this by
535 * one more interval if we are already firing exactly on the
536 * interval to find the earliest value _after_ now_ns.
537 *
538 * - If now_ns > last_val -- which happens iff !backwards,
539 * i.e., the clock ran fast -- then remainder is zero or
540 * positive positive, so this finds the _latest_ value not
541 * later than now_ns. We will always advance this by one
542 * more interval to find the earliest value _after_ now_ns.
543 * We will also count overflows.
544 *
545 * (now_ns == last_val is not possible at this point because it
546 * only happens if the addition of struct timespec would
547 * overflow, and that is only possible when timespec2ns would
548 * also overflow for at least one of the inputs.)
549 */
550 KASSERT(last_val != now_ns);
551 remainder = (now_ns - last_val) % interval;
552 next_val = now_ns - remainder;
553 KASSERT((last_val - next_val) % interval == 0);
554 if (backwards) {
555 /*
556 * If the clock was wound back to an exact multiple of
557 * the interval, so next_val = now_ns, don't demand to
558 * fire again in the same instant -- advance to the
559 * next interval. Overflow is not possible; proof is
560 * asserted.
561 */
562 if (remainder == 0) {
563 KASSERT(now_ns < last_val);
564 KASSERT(next_val == now_ns);
565 KASSERT(last_val - next_val >= interval);
566 KASSERT(interval <= last_val - next_val);
567 KASSERT(next_val <= last_val - interval);
568 KASSERT(next_val <= INT64_MAX - interval);
569 next_val += interval;
570 }
571 } else {
572 /*
573 * next_val is the largest integer multiple of interval
574 * not later than now_ns. Count the number of full
575 * intervals that were skipped (division should be
576 * exact here), not counting any partial interval
577 * between next_val and now_ns, as the number of
578 * overruns. Advance by one interval -- unless that
579 * would overflow.
580 */
581 *overrunsp += MIN(INT_MAX - *overrunsp,
582 (next_val - last_val) / interval);
583 if (__predict_false(next_val > INT64_MAX - interval))
584 goto overflow;
585 next_val += interval;
586 }
587
588 next->tv_sec = next_val / 1000000000;
589 next->tv_nsec = next_val % 1000000000;
590 return;
591
592 overflow:
593 next->tv_sec = 0;
594 next->tv_nsec = 0;
595 }
596