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