1 /* $NetBSD: subr_time_arith.c,v 1.7 2026/01/04 03:21:19 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.7 2026/01/04 03:21:19 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/sdt.h> 78 #include <sys/systm.h> 79 80 #include <machine/limits.h> 81 82 #elif defined(_TIME_TESTING) 83 84 #include <assert.h> 85 #include <limits.h> 86 #include <stdbool.h> 87 88 extern int hz; 89 extern int tick; 90 91 #define KASSERT assert 92 #define MIN(X, Y) ((X) < (Y) ? (X) : (Y)) 93 #define SET_ERROR(E) (E) 94 95 #endif 96 97 /* 98 * Compute number of ticks in the specified amount of time. 99 */ 100 int 101 tvtohz(const struct timeval *tv) 102 { 103 unsigned long ticks; 104 long sec, usec; 105 106 /* 107 * If the number of usecs in the whole seconds part of the time 108 * difference fits in a long, then the total number of usecs will 109 * fit in an unsigned long. Compute the total and convert it to 110 * ticks, rounding up and adding 1 to allow for the current tick 111 * to expire. Rounding also depends on unsigned long arithmetic 112 * to avoid overflow. 113 * 114 * Otherwise, if the number of ticks in the whole seconds part of 115 * the time difference fits in a long, then convert the parts to 116 * ticks separately and add, using similar rounding methods and 117 * overflow avoidance. This method would work in the previous 118 * case, but it is slightly slower and assumes that hz is integral. 119 * 120 * Otherwise, round the time difference down to the maximum 121 * representable value. 122 * 123 * If ints are 32-bit, then the maximum value for any timeout in 124 * 10ms ticks is 248 days. 125 */ 126 sec = tv->tv_sec; 127 usec = tv->tv_usec; 128 129 KASSERT(usec >= 0); 130 KASSERT(usec < 1000000); 131 132 /* catch overflows in conversion time_t->int */ 133 if (tv->tv_sec > INT_MAX) 134 return INT_MAX; 135 if (tv->tv_sec < 0) 136 return 0; 137 138 if (sec < 0 || (sec == 0 && usec == 0)) { 139 /* 140 * Would expire now or in the past. Return 0 ticks. 141 * This is different from the legacy tvhzto() interface, 142 * and callers need to check for it. 143 */ 144 ticks = 0; 145 } else if (sec <= (LONG_MAX / 1000000)) 146 ticks = (((sec * 1000000) + (unsigned long)usec + (tick - 1)) 147 / tick) + 1; 148 else if (sec <= (LONG_MAX / hz)) 149 ticks = (sec * hz) + 150 (((unsigned long)usec + (tick - 1)) / tick) + 1; 151 else 152 ticks = LONG_MAX; 153 154 if (ticks > INT_MAX) 155 ticks = INT_MAX; 156 157 return ((int)ticks); 158 } 159 160 /* 161 * Compute number of ticks in the specified amount of time. 162 * 163 * Round up, clamped to INT_MAX. Return 0 iff ts <= 0. 164 */ 165 int 166 tstohz(const struct timespec *ts) 167 { 168 struct timeval tv; 169 170 KASSERT(ts->tv_nsec >= 0); 171 KASSERT(ts->tv_nsec < 1000000000); 172 173 /* 174 * usec has great enough resolution for hz, so convert to a 175 * timeval and use tvtohz() above. 176 */ 177 tv.tv_sec = ts->tv_sec; 178 tv.tv_usec = (ts->tv_nsec + 999)/1000; 179 if (tv.tv_usec >= 1000000) { 180 if (__predict_false(tv.tv_sec == __type_max(time_t))) 181 return INT_MAX; 182 tv.tv_sec++; 183 tv.tv_usec -= 1000000; 184 } 185 return tvtohz(&tv); 186 } 187 188 /* 189 * Check that a proposed value to load into the .it_value or 190 * .it_interval part of an interval timer is acceptable, and 191 * fix it to have at least minimal value (i.e. if it is less 192 * than the resolution of the clock, round it up.). We don't 193 * timeout the 0,0 value because this means to disable the 194 * timer or the interval. 195 */ 196 int 197 itimerfix(struct timeval *tv) 198 { 199 200 if (tv->tv_usec < 0 || tv->tv_usec >= 1000000) 201 return SET_ERROR(EINVAL); 202 if (tv->tv_sec < 0) 203 return SET_ERROR(ETIMEDOUT); 204 if (tv->tv_sec == 0 && tv->tv_usec != 0 && tv->tv_usec < tick) 205 tv->tv_usec = tick; 206 return 0; 207 } 208 209 int 210 itimespecfix(struct timespec *ts) 211 { 212 213 if (ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000) 214 return SET_ERROR(EINVAL); 215 if (ts->tv_sec < 0) 216 return SET_ERROR(ETIMEDOUT); 217 if (ts->tv_sec == 0 && ts->tv_nsec != 0 && ts->tv_nsec < tick * 1000) 218 ts->tv_nsec = tick * 1000; 219 return 0; 220 } 221 222 /* 223 * timespecaddok(tsp, usp) 224 * 225 * True if tsp + usp can be computed without overflow, i.e., if it 226 * is OK to do timespecadd(tsp, usp, ...). 227 */ 228 bool 229 timespecaddok(const struct timespec *tsp, const struct timespec *usp) 230 { 231 enum { TIME_MIN = __type_min(time_t), TIME_MAX = __type_max(time_t) }; 232 time_t a = tsp->tv_sec; 233 time_t b = usp->tv_sec; 234 bool carry; 235 236 /* 237 * Caller is responsible for guaranteeing valid timespec 238 * inputs. Any user-controlled inputs must be validated or 239 * adjusted. 240 */ 241 KASSERT(tsp->tv_nsec >= 0); 242 KASSERT(usp->tv_nsec >= 0); 243 KASSERT(tsp->tv_nsec < 1000000000L); 244 KASSERT(usp->tv_nsec < 1000000000L); 245 __CTASSERT(1000000000L <= __type_max(long) - 1000000000L); 246 247 /* 248 * Fail if a + b + carry overflows TIME_MAX, or if a + b 249 * overflows TIME_MIN because timespecadd adds the carry after 250 * computing a + b. 251 * 252 * Break it into two mutually exclusive and exhaustive cases: 253 * I. a >= 0 254 * II. a < 0 255 */ 256 carry = (tsp->tv_nsec + usp->tv_nsec >= 1000000000L); 257 if (a >= 0) { 258 /* 259 * Case I: a >= 0. If b < 0, then b + 1 <= 0, so 260 * 261 * a + b + 1 <= a + 0 <= TIME_MAX, 262 * 263 * and 264 * 265 * a + b >= 0 + b = b >= TIME_MIN, 266 * 267 * so this can't overflow. 268 * 269 * If b >= 0, then a + b + carry >= a + b >= 0, so 270 * negative results and thus results below TIME_MIN are 271 * impossible; we need only avoid 272 * 273 * a + b + carry > TIME_MAX, 274 * 275 * which we will do by rejecting if 276 * 277 * b > TIME_MAX - a - carry, 278 * 279 * which in turn is incidentally always false if b < 0 280 * so we don't need extra logic to discriminate on the 281 * b >= 0 and b < 0 cases. 282 * 283 * Since 0 <= a <= TIME_MAX, we know 284 * 285 * 0 <= TIME_MAX - a <= TIME_MAX, 286 * 287 * and hence 288 * 289 * -1 <= TIME_MAX - a - 1 < TIME_MAX. 290 * 291 * So we can compute TIME_MAX - a - carry (i.e., either 292 * TIME_MAX - a or TIME_MAX - a - 1) safely without 293 * overflow. 294 */ 295 if (b > TIME_MAX - a - carry) 296 return false; 297 } else { 298 /* 299 * Case II: a < 0. If b >= 0, then since a + 1 <= 0, 300 * we have 301 * 302 * a + b + 1 <= b <= TIME_MAX, 303 * 304 * and 305 * 306 * a + b >= a >= TIME_MIN, 307 * 308 * so this can't overflow. 309 * 310 * If b < 0, then the intermediate a + b is negative 311 * and the outcome a + b + 1 is nonpositive, so we need 312 * only avoid 313 * 314 * a + b < TIME_MIN, 315 * 316 * which we will do by rejecting if 317 * 318 * a < TIME_MIN - b. 319 * 320 * (Reminder: The carry is added afterward in 321 * timespecadd, so to avoid overflow it is not enough 322 * to merely reject a + b + carry < TIME_MIN.) 323 * 324 * It is safe to compute the difference TIME_MIN - b 325 * because b is negative, so the result lies in 326 * (TIME_MIN, 0]. 327 */ 328 if (b < 0 && a < TIME_MIN - b) 329 return false; 330 } 331 332 return true; 333 } 334 335 /* 336 * timespecsubok(tsp, usp) 337 * 338 * True if tsp - usp can be computed without overflow, i.e., if it 339 * is OK to do timespecsub(tsp, usp, ...). 340 */ 341 bool 342 timespecsubok(const struct timespec *tsp, const struct timespec *usp) 343 { 344 enum { TIME_MIN = __type_min(time_t), TIME_MAX = __type_max(time_t) }; 345 time_t a = tsp->tv_sec, b = usp->tv_sec; 346 bool borrow; 347 348 /* 349 * Caller is responsible for guaranteeing valid timespec 350 * inputs. Any user-controlled inputs must be validated or 351 * adjusted. 352 */ 353 KASSERT(tsp->tv_nsec >= 0); 354 KASSERT(usp->tv_nsec >= 0); 355 KASSERT(tsp->tv_nsec < 1000000000L); 356 KASSERT(usp->tv_nsec < 1000000000L); 357 __CTASSERT(1000000000L <= __type_max(long) - 1000000000L); 358 359 /* 360 * Fail if a - b - borrow overflows TIME_MIN, or if a - b 361 * overflows TIME_MAX because timespecsub subtracts the borrow 362 * after computing a - b. 363 * 364 * Break it into two mutually exclusive and exhaustive cases: 365 * I. a < 0 366 * II. a >= 0 367 */ 368 borrow = (tsp->tv_nsec - usp->tv_nsec < 0); 369 if (a < 0) { 370 /* 371 * Case I: a < 0. If b < 0, then -b - 1 >= 0, so 372 * 373 * a - b - 1 >= a + 0 >= TIME_MIN, 374 * 375 * and, since a <= -1, provided that TIME_MIN <= 376 * -TIME_MAX - 1 so that TIME_MAX <= -TIME_MIN - 1 (in 377 * fact, equality holds, under the assumption of 378 * two's-complement arithmetic), 379 * 380 * a - b <= -1 - b = -b - 1 <= TIME_MAX, 381 * 382 * so this can't overflow. 383 */ 384 __CTASSERT(TIME_MIN <= -TIME_MAX - 1); 385 386 /* 387 * If b >= 0, then a - b - borrow <= a - b < 0, so 388 * positive results and thus results above TIME_MAX are 389 * impossible; we need only avoid 390 * 391 * a - b - borrow < TIME_MIN, 392 * 393 * which we will do by rejecting if 394 * 395 * a < TIME_MIN + b + borrow. 396 * 397 * The right-hand side is safe to evaluate for any 398 * values of b and borrow as long as TIME_MIN + 399 * TIME_MAX + 1 <= TIME_MAX, i.e., TIME_MIN <= -1. 400 * (Note: If time_t were unsigned, this would fail!) 401 * 402 * Note: Unlike Case I in timespecaddok, this criterion 403 * does not work for b < 0, nor can the roles of a and 404 * b in the inequality be reversed (e.g., -b < TIME_MIN 405 * - a + borrow) without extra cases like checking for 406 * b = TEST_MIN. 407 */ 408 __CTASSERT(TIME_MIN < -1); 409 if (b >= 0 && a < TIME_MIN + b + borrow) 410 return false; 411 } else { 412 /* 413 * Case II: a >= 0. If b >= 0, then 414 * 415 * a - b <= a <= TIME_MAX, 416 * 417 * and, provided TIME_MIN <= -TIME_MAX - 1 (in fact, 418 * equality holds, under the assumption of 419 * two's-complement arithmetic) 420 * 421 * a - b - 1 >= -b - 1 >= -TIME_MAX - 1 >= TIME_MIN, 422 * 423 * so this can't overflow. 424 */ 425 __CTASSERT(TIME_MIN <= -TIME_MAX - 1); 426 427 /* 428 * If b < 0, then a - b >= a >= 0, so negative results 429 * and thus results below TIME_MIN are impossible; we 430 * need only avoid 431 * 432 * a - b > TIME_MAX, 433 * 434 * which we will do by rejecting if 435 * 436 * a > TIME_MAX + b. 437 * 438 * (Reminder: The borrow is subtracted afterward in 439 * timespecsub, so to avoid overflow it is not enough 440 * to merely reject a - b - borrow > TIME_MAX.) 441 * 442 * It is safe to compute the sum TIME_MAX + b because b 443 * is negative, so the result lies in [0, TIME_MAX). 444 */ 445 if (b < 0 && a > TIME_MAX + b) 446 return false; 447 } 448 449 return true; 450 } 451 452 static bool 453 timespec2nsok(const struct timespec *ts) 454 { 455 456 return ts->tv_sec < INT64_MAX/1000000000 || 457 (ts->tv_sec == INT64_MAX/1000000000 && 458 ts->tv_nsec <= INT64_MAX - (INT64_MAX/1000000000)*1000000000); 459 } 460 461 /* 462 * itimer_transition(it, now, next, &overruns) 463 * 464 * Given: 465 * 466 * - it: the current state of an itimer (it_value = last expiry 467 * time, it_interval = periodic rescheduling interval), and 468 * 469 * - now: the current time on the itimer's clock; 470 * 471 * compute: 472 * 473 * - next: the next time the itimer should be scheduled for, and 474 * - overruns: the number of overruns if we're firing late. 475 * 476 * XXX This should maybe also say whether the itimer should expire 477 * at all. 478 */ 479 void 480 itimer_transition(const struct itimerspec *restrict it, 481 const struct timespec *restrict now, 482 struct timespec *restrict next, 483 int *restrict overrunsp) 484 { 485 int64_t last_val, next_val, interval, remainder, now_ns; 486 int backwards; 487 488 /* 489 * Zero the outputs so we can test assertions in userland 490 * without undefined behaviour. 491 */ 492 timespecclear(next); 493 *overrunsp = 0; 494 495 /* 496 * Paranoia: Caller should guarantee this. 497 */ 498 if (!timespecisset(&it->it_interval)) { 499 timespecclear(next); 500 return; 501 } 502 503 /* Did the clock wind backwards? */ 504 backwards = (timespeccmp(&it->it_value, now, >)); 505 506 /* Valid value and interval guaranteed by itimerfix. */ 507 KASSERT(it->it_value.tv_sec >= 0); 508 KASSERT(it->it_value.tv_nsec < 1000000000); 509 KASSERT(it->it_interval.tv_sec >= 0); 510 KASSERT(it->it_interval.tv_nsec < 1000000000); 511 512 /* Nonnegative interval guaranteed by itimerfix. */ 513 KASSERT(it->it_interval.tv_sec >= 0); 514 KASSERT(it->it_interval.tv_nsec >= 0); 515 516 /* Handle the easy case of non-overflown timers first. */ 517 if (__predict_true(!backwards)) { 518 if (__predict_false(!timespecaddok(&it->it_value, 519 &it->it_interval))) 520 goto overflow; 521 timespecadd(&it->it_value, &it->it_interval, next); 522 if (__predict_true(timespeccmp(now, next, <))) 523 return; 524 } 525 526 /* 527 * If we can't represent the input as a number of nanoseconds, 528 * bail. This is good up to the year 2262, if we start 529 * counting from 1970 (2^63 nanoseconds ~ 292 years). 530 */ 531 if (__predict_false(!timespec2nsok(now)) || 532 __predict_false(!timespec2nsok(&it->it_value)) || 533 __predict_false(!timespec2nsok(&it->it_interval))) 534 goto overflow; 535 536 now_ns = timespec2ns(now); 537 last_val = timespec2ns(&it->it_value); 538 interval = timespec2ns(&it->it_interval); 539 540 KASSERT(now_ns >= 0); 541 KASSERT(last_val >= 0); 542 KASSERT(interval >= 0); 543 544 /* 545 * now [backwards] overruns now [forwards] 546 * | v v v | 547 * |--+----+-*--x----+----+----|----+----+----+--*-x----+--> 548 * \/ | \/ 549 * remainder last_val remainder 550 * (zero or negative) (zero or positive) 551 * 552 * Set next_val to last_value + k*interval for some k. 553 * 554 * The interval is always positive, and division in C 555 * truncates, so dividing a positive duration by the interval 556 * always gives zero or a positive remainder, and dividing a 557 * negative duration by the interval always gives zero or a 558 * negative remainder. Hence: 559 * 560 * - If now_ns < last_val -- which happens iff backwards, i.e., 561 * the clock was wound backwards -- then remainder is zero or 562 * negative, so subtracting it stays in place or moves 563 * forward in time, and thus this finds the _earliest_ value 564 * that is not earlier than now_ns. We will advance this by 565 * one more interval if we are already firing exactly on the 566 * interval to find the earliest value _after_ now_ns. 567 * 568 * - If now_ns > last_val -- which happens iff !backwards, 569 * i.e., the clock ran fast -- then remainder is zero or 570 * positive positive, so this finds the _latest_ value not 571 * later than now_ns. We will always advance this by one 572 * more interval to find the earliest value _after_ now_ns. 573 * We will also count overflows. 574 * 575 * (now_ns == last_val is not possible at this point because it 576 * only happens if the addition of struct timespec would 577 * overflow, and that is only possible when timespec2ns would 578 * also overflow for at least one of the inputs.) 579 */ 580 KASSERT(last_val != now_ns); 581 remainder = (now_ns - last_val) % interval; 582 next_val = now_ns - remainder; 583 KASSERT((last_val - next_val) % interval == 0); 584 if (backwards) { 585 /* 586 * If the clock was wound back to an exact multiple of 587 * the interval, so next_val = now_ns, don't demand to 588 * fire again in the same instant -- advance to the 589 * next interval. Overflow is not possible; proof is 590 * asserted. 591 */ 592 if (remainder == 0) { 593 KASSERT(now_ns < last_val); 594 KASSERT(next_val == now_ns); 595 KASSERT(last_val - next_val >= interval); 596 KASSERT(interval <= last_val - next_val); 597 KASSERT(next_val <= last_val - interval); 598 KASSERT(next_val <= INT64_MAX - interval); 599 next_val += interval; 600 } 601 } else { 602 /* 603 * next_val is the largest integer multiple of interval 604 * not later than now_ns. Count the number of full 605 * intervals that were skipped (division should be 606 * exact here), not counting any partial interval 607 * between next_val and now_ns, as the number of 608 * overruns. Advance by one interval -- unless that 609 * would overflow. 610 */ 611 *overrunsp = MIN(INT_MAX, (next_val - last_val) / interval); 612 if (__predict_false(next_val > INT64_MAX - interval)) 613 goto overflow; 614 next_val += interval; 615 } 616 617 next->tv_sec = next_val / 1000000000; 618 next->tv_nsec = next_val % 1000000000; 619 return; 620 621 overflow: 622 next->tv_sec = 0; 623 next->tv_nsec = 0; 624 } 625