1 /* 2 * Copyright (c) 2003,2004 The DragonFly Project. All rights reserved. 3 * 4 * This code is derived from software contributed to The DragonFly Project 5 * by Matthew Dillon <dillon@backplane.com> 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 * 11 * 1. Redistributions of source code must retain the above copyright 12 * notice, this list of conditions and the following disclaimer. 13 * 2. Redistributions in binary form must reproduce the above copyright 14 * notice, this list of conditions and the following disclaimer in 15 * the documentation and/or other materials provided with the 16 * distribution. 17 * 3. Neither the name of The DragonFly Project nor the names of its 18 * contributors may be used to endorse or promote products derived 19 * from this software without specific, prior written permission. 20 * 21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 24 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 25 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 26 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, 27 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 28 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 29 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 30 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 31 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 32 * SUCH DAMAGE. 33 * 34 * Copyright (c) 1997, 1998 Poul-Henning Kamp <phk@FreeBSD.org> 35 * Copyright (c) 1982, 1986, 1991, 1993 36 * The Regents of the University of California. All rights reserved. 37 * (c) UNIX System Laboratories, Inc. 38 * All or some portions of this file are derived from material licensed 39 * to the University of California by American Telephone and Telegraph 40 * Co. or Unix System Laboratories, Inc. and are reproduced herein with 41 * the permission of UNIX System Laboratories, Inc. 42 * 43 * Redistribution and use in source and binary forms, with or without 44 * modification, are permitted provided that the following conditions 45 * are met: 46 * 1. Redistributions of source code must retain the above copyright 47 * notice, this list of conditions and the following disclaimer. 48 * 2. Redistributions in binary form must reproduce the above copyright 49 * notice, this list of conditions and the following disclaimer in the 50 * documentation and/or other materials provided with the distribution. 51 * 3. All advertising materials mentioning features or use of this software 52 * must display the following acknowledgement: 53 * This product includes software developed by the University of 54 * California, Berkeley and its contributors. 55 * 4. Neither the name of the University nor the names of its contributors 56 * may be used to endorse or promote products derived from this software 57 * without specific prior written permission. 58 * 59 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 60 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 61 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 62 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 63 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 64 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 65 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 66 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 67 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 68 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 69 * SUCH DAMAGE. 70 * 71 * @(#)kern_clock.c 8.5 (Berkeley) 1/21/94 72 * $FreeBSD: src/sys/kern/kern_clock.c,v 1.105.2.10 2002/10/17 13:19:40 maxim Exp $ 73 * $DragonFly: src/sys/kern/kern_clock.c,v 1.53 2006/06/08 18:25:46 dillon Exp $ 74 */ 75 76 #include "opt_ntp.h" 77 #include "opt_polling.h" 78 #include "opt_pctrack.h" 79 80 #include <sys/param.h> 81 #include <sys/systm.h> 82 #include <sys/callout.h> 83 #include <sys/kernel.h> 84 #include <sys/kinfo.h> 85 #include <sys/proc.h> 86 #include <sys/malloc.h> 87 #include <sys/resourcevar.h> 88 #include <sys/signalvar.h> 89 #include <sys/timex.h> 90 #include <sys/timepps.h> 91 #include <vm/vm.h> 92 #include <sys/lock.h> 93 #include <vm/pmap.h> 94 #include <vm/vm_map.h> 95 #include <vm/vm_extern.h> 96 #include <sys/sysctl.h> 97 #include <sys/thread2.h> 98 99 #include <machine/cpu.h> 100 #include <machine/limits.h> 101 #include <machine/smp.h> 102 103 #ifdef GPROF 104 #include <sys/gmon.h> 105 #endif 106 107 #ifdef DEVICE_POLLING 108 extern void init_device_poll(void); 109 #endif 110 111 #ifdef DEBUG_PCTRACK 112 static void do_pctrack(struct intrframe *frame, int which); 113 #endif 114 115 static void initclocks (void *dummy); 116 SYSINIT(clocks, SI_SUB_CLOCKS, SI_ORDER_FIRST, initclocks, NULL) 117 118 /* 119 * Some of these don't belong here, but it's easiest to concentrate them. 120 * Note that cpu_time counts in microseconds, but most userland programs 121 * just compare relative times against the total by delta. 122 */ 123 struct kinfo_cputime cputime_percpu[MAXCPU]; 124 #ifdef DEBUG_PCTRACK 125 struct kinfo_pcheader cputime_pcheader = { PCTRACK_SIZE, PCTRACK_ARYSIZE }; 126 struct kinfo_pctrack cputime_pctrack[MAXCPU][PCTRACK_SIZE]; 127 #endif 128 129 #ifdef SMP 130 static int 131 sysctl_cputime(SYSCTL_HANDLER_ARGS) 132 { 133 int cpu, error = 0; 134 size_t size = sizeof(struct kinfo_cputime); 135 136 for (cpu = 0; cpu < ncpus; ++cpu) { 137 if ((error = SYSCTL_OUT(req, &cputime_percpu[cpu], size))) 138 break; 139 } 140 141 return (error); 142 } 143 SYSCTL_PROC(_kern, OID_AUTO, cputime, (CTLTYPE_OPAQUE|CTLFLAG_RD), 0, 0, 144 sysctl_cputime, "S,kinfo_cputime", "CPU time statistics"); 145 #else 146 SYSCTL_STRUCT(_kern, OID_AUTO, cputime, CTLFLAG_RD, &cpu_time, kinfo_cputime, 147 "CPU time statistics"); 148 #endif 149 150 /* 151 * boottime is used to calculate the 'real' uptime. Do not confuse this with 152 * microuptime(). microtime() is not drift compensated. The real uptime 153 * with compensation is nanotime() - bootime. boottime is recalculated 154 * whenever the real time is set based on the compensated elapsed time 155 * in seconds (gd->gd_time_seconds). 156 * 157 * The gd_time_seconds and gd_cpuclock_base fields remain fairly monotonic. 158 * Slight adjustments to gd_cpuclock_base are made to phase-lock it to 159 * the real time. 160 */ 161 struct timespec boottime; /* boot time (realtime) for reference only */ 162 time_t time_second; /* read-only 'passive' uptime in seconds */ 163 164 /* 165 * basetime is used to calculate the compensated real time of day. The 166 * basetime can be modified on a per-tick basis by the adjtime(), 167 * ntp_adjtime(), and sysctl-based time correction APIs. 168 * 169 * Note that frequency corrections can also be made by adjusting 170 * gd_cpuclock_base. 171 * 172 * basetime is a tail-chasing FIFO, updated only by cpu #0. The FIFO is 173 * used on both SMP and UP systems to avoid MP races between cpu's and 174 * interrupt races on UP systems. 175 */ 176 #define BASETIME_ARYSIZE 16 177 #define BASETIME_ARYMASK (BASETIME_ARYSIZE - 1) 178 static struct timespec basetime[BASETIME_ARYSIZE]; 179 static volatile int basetime_index; 180 181 static int 182 sysctl_get_basetime(SYSCTL_HANDLER_ARGS) 183 { 184 struct timespec *bt; 185 int error; 186 int index; 187 188 /* 189 * Because basetime data and index may be updated by another cpu, 190 * a load fence is required to ensure that the data we read has 191 * not been speculatively read relative to a possibly updated index. 192 */ 193 index = basetime_index; 194 cpu_lfence(); 195 bt = &basetime[index]; 196 error = SYSCTL_OUT(req, bt, sizeof(*bt)); 197 return (error); 198 } 199 200 SYSCTL_STRUCT(_kern, KERN_BOOTTIME, boottime, CTLFLAG_RD, 201 &boottime, timespec, "System boottime"); 202 SYSCTL_PROC(_kern, OID_AUTO, basetime, CTLTYPE_STRUCT|CTLFLAG_RD, 0, 0, 203 sysctl_get_basetime, "S,timespec", "System basetime"); 204 205 static void hardclock(systimer_t info, struct intrframe *frame); 206 static void statclock(systimer_t info, struct intrframe *frame); 207 static void schedclock(systimer_t info, struct intrframe *frame); 208 static void getnanotime_nbt(struct timespec *nbt, struct timespec *tsp); 209 210 int ticks; /* system master ticks at hz */ 211 int clocks_running; /* tsleep/timeout clocks operational */ 212 int64_t nsec_adj; /* ntpd per-tick adjustment in nsec << 32 */ 213 int64_t nsec_acc; /* accumulator */ 214 215 /* NTPD time correction fields */ 216 int64_t ntp_tick_permanent; /* per-tick adjustment in nsec << 32 */ 217 int64_t ntp_tick_acc; /* accumulator for per-tick adjustment */ 218 int64_t ntp_delta; /* one-time correction in nsec */ 219 int64_t ntp_big_delta = 1000000000; 220 int32_t ntp_tick_delta; /* current adjustment rate */ 221 int32_t ntp_default_tick_delta; /* adjustment rate for ntp_delta */ 222 time_t ntp_leap_second; /* time of next leap second */ 223 int ntp_leap_insert; /* whether to insert or remove a second */ 224 225 /* 226 * Finish initializing clock frequencies and start all clocks running. 227 */ 228 /* ARGSUSED*/ 229 static void 230 initclocks(void *dummy) 231 { 232 cpu_initclocks(); 233 #ifdef DEVICE_POLLING 234 init_device_poll(); 235 #endif 236 /*psratio = profhz / stathz;*/ 237 initclocks_pcpu(); 238 clocks_running = 1; 239 } 240 241 /* 242 * Called on a per-cpu basis 243 */ 244 void 245 initclocks_pcpu(void) 246 { 247 struct globaldata *gd = mycpu; 248 249 crit_enter(); 250 if (gd->gd_cpuid == 0) { 251 gd->gd_time_seconds = 1; 252 gd->gd_cpuclock_base = sys_cputimer->count(); 253 } else { 254 /* XXX */ 255 gd->gd_time_seconds = globaldata_find(0)->gd_time_seconds; 256 gd->gd_cpuclock_base = globaldata_find(0)->gd_cpuclock_base; 257 } 258 259 /* 260 * Use a non-queued periodic systimer to prevent multiple ticks from 261 * building up if the sysclock jumps forward (8254 gets reset). The 262 * sysclock will never jump backwards. Our time sync is based on 263 * the actual sysclock, not the ticks count. 264 */ 265 systimer_init_periodic_nq(&gd->gd_hardclock, hardclock, NULL, hz); 266 systimer_init_periodic_nq(&gd->gd_statclock, statclock, NULL, stathz); 267 /* XXX correct the frequency for scheduler / estcpu tests */ 268 systimer_init_periodic_nq(&gd->gd_schedclock, schedclock, 269 NULL, ESTCPUFREQ); 270 crit_exit(); 271 } 272 273 /* 274 * This sets the current real time of day. Timespecs are in seconds and 275 * nanoseconds. We do not mess with gd_time_seconds and gd_cpuclock_base, 276 * instead we adjust basetime so basetime + gd_* results in the current 277 * time of day. This way the gd_* fields are guarenteed to represent 278 * a monotonically increasing 'uptime' value. 279 * 280 * When set_timeofday() is called from userland, the system call forces it 281 * onto cpu #0 since only cpu #0 can update basetime_index. 282 */ 283 void 284 set_timeofday(struct timespec *ts) 285 { 286 struct timespec *nbt; 287 int ni; 288 289 /* 290 * XXX SMP / non-atomic basetime updates 291 */ 292 crit_enter(); 293 ni = (basetime_index + 1) & BASETIME_ARYMASK; 294 nbt = &basetime[ni]; 295 nanouptime(nbt); 296 nbt->tv_sec = ts->tv_sec - nbt->tv_sec; 297 nbt->tv_nsec = ts->tv_nsec - nbt->tv_nsec; 298 if (nbt->tv_nsec < 0) { 299 nbt->tv_nsec += 1000000000; 300 --nbt->tv_sec; 301 } 302 303 /* 304 * Note that basetime diverges from boottime as the clock drift is 305 * compensated for, so we cannot do away with boottime. When setting 306 * the absolute time of day the drift is 0 (for an instant) and we 307 * can simply assign boottime to basetime. 308 * 309 * Note that nanouptime() is based on gd_time_seconds which is drift 310 * compensated up to a point (it is guarenteed to remain monotonically 311 * increasing). gd_time_seconds is thus our best uptime guess and 312 * suitable for use in the boottime calculation. It is already taken 313 * into account in the basetime calculation above. 314 */ 315 boottime.tv_sec = nbt->tv_sec; 316 ntp_delta = 0; 317 318 /* 319 * We now have a new basetime, make sure all other cpus have it, 320 * then update the index. 321 */ 322 cpu_sfence(); 323 basetime_index = ni; 324 325 crit_exit(); 326 } 327 328 /* 329 * Each cpu has its own hardclock, but we only increments ticks and softticks 330 * on cpu #0. 331 * 332 * NOTE! systimer! the MP lock might not be held here. We can only safely 333 * manipulate objects owned by the current cpu. 334 */ 335 static void 336 hardclock(systimer_t info, struct intrframe *frame) 337 { 338 sysclock_t cputicks; 339 struct proc *p; 340 struct pstats *pstats; 341 struct globaldata *gd = mycpu; 342 343 /* 344 * Realtime updates are per-cpu. Note that timer corrections as 345 * returned by microtime() and friends make an additional adjustment 346 * using a system-wise 'basetime', but the running time is always 347 * taken from the per-cpu globaldata area. Since the same clock 348 * is distributing (XXX SMP) to all cpus, the per-cpu timebases 349 * stay in synch. 350 * 351 * Note that we never allow info->time (aka gd->gd_hardclock.time) 352 * to reverse index gd_cpuclock_base, but that it is possible for 353 * it to temporarily get behind in the seconds if something in the 354 * system locks interrupts for a long period of time. Since periodic 355 * timers count events, though everything should resynch again 356 * immediately. 357 */ 358 cputicks = info->time - gd->gd_cpuclock_base; 359 if (cputicks >= sys_cputimer->freq) { 360 ++gd->gd_time_seconds; 361 gd->gd_cpuclock_base += sys_cputimer->freq; 362 } 363 364 /* 365 * The system-wide ticks counter and NTP related timedelta/tickdelta 366 * adjustments only occur on cpu #0. NTP adjustments are accomplished 367 * by updating basetime. 368 */ 369 if (gd->gd_cpuid == 0) { 370 struct timespec *nbt; 371 struct timespec nts; 372 int leap; 373 int ni; 374 375 ++ticks; 376 377 #if 0 378 if (tco->tc_poll_pps) 379 tco->tc_poll_pps(tco); 380 #endif 381 382 /* 383 * Calculate the new basetime index. We are in a critical section 384 * on cpu #0 and can safely play with basetime_index. Start 385 * with the current basetime and then make adjustments. 386 */ 387 ni = (basetime_index + 1) & BASETIME_ARYMASK; 388 nbt = &basetime[ni]; 389 *nbt = basetime[basetime_index]; 390 391 /* 392 * Apply adjtime corrections. (adjtime() API) 393 * 394 * adjtime() only runs on cpu #0 so our critical section is 395 * sufficient to access these variables. 396 */ 397 if (ntp_delta != 0) { 398 nbt->tv_nsec += ntp_tick_delta; 399 ntp_delta -= ntp_tick_delta; 400 if ((ntp_delta > 0 && ntp_delta < ntp_tick_delta) || 401 (ntp_delta < 0 && ntp_delta > ntp_tick_delta)) { 402 ntp_tick_delta = ntp_delta; 403 } 404 } 405 406 /* 407 * Apply permanent frequency corrections. (sysctl API) 408 */ 409 if (ntp_tick_permanent != 0) { 410 ntp_tick_acc += ntp_tick_permanent; 411 if (ntp_tick_acc >= (1LL << 32)) { 412 nbt->tv_nsec += ntp_tick_acc >> 32; 413 ntp_tick_acc -= (ntp_tick_acc >> 32) << 32; 414 } else if (ntp_tick_acc <= -(1LL << 32)) { 415 /* Negate ntp_tick_acc to avoid shifting the sign bit. */ 416 nbt->tv_nsec -= (-ntp_tick_acc) >> 32; 417 ntp_tick_acc += ((-ntp_tick_acc) >> 32) << 32; 418 } 419 } 420 421 if (nbt->tv_nsec >= 1000000000) { 422 nbt->tv_sec++; 423 nbt->tv_nsec -= 1000000000; 424 } else if (nbt->tv_nsec < 0) { 425 nbt->tv_sec--; 426 nbt->tv_nsec += 1000000000; 427 } 428 429 /* 430 * Another per-tick compensation. (for ntp_adjtime() API) 431 */ 432 if (nsec_adj != 0) { 433 nsec_acc += nsec_adj; 434 if (nsec_acc >= 0x100000000LL) { 435 nbt->tv_nsec += nsec_acc >> 32; 436 nsec_acc = (nsec_acc & 0xFFFFFFFFLL); 437 } else if (nsec_acc <= -0x100000000LL) { 438 nbt->tv_nsec -= -nsec_acc >> 32; 439 nsec_acc = -(-nsec_acc & 0xFFFFFFFFLL); 440 } 441 if (nbt->tv_nsec >= 1000000000) { 442 nbt->tv_nsec -= 1000000000; 443 ++nbt->tv_sec; 444 } else if (nbt->tv_nsec < 0) { 445 nbt->tv_nsec += 1000000000; 446 --nbt->tv_sec; 447 } 448 } 449 450 /************************************************************ 451 * LEAP SECOND CORRECTION * 452 ************************************************************ 453 * 454 * Taking into account all the corrections made above, figure 455 * out the new real time. If the seconds field has changed 456 * then apply any pending leap-second corrections. 457 */ 458 getnanotime_nbt(nbt, &nts); 459 460 if (time_second != nts.tv_sec) { 461 /* 462 * Apply leap second (sysctl API). Adjust nts for changes 463 * so we do not have to call getnanotime_nbt again. 464 */ 465 if (ntp_leap_second) { 466 if (ntp_leap_second == nts.tv_sec) { 467 if (ntp_leap_insert) { 468 nbt->tv_sec++; 469 nts.tv_sec++; 470 } else { 471 nbt->tv_sec--; 472 nts.tv_sec--; 473 } 474 ntp_leap_second--; 475 } 476 } 477 478 /* 479 * Apply leap second (ntp_adjtime() API), calculate a new 480 * nsec_adj field. ntp_update_second() returns nsec_adj 481 * as a per-second value but we need it as a per-tick value. 482 */ 483 leap = ntp_update_second(time_second, &nsec_adj); 484 nsec_adj /= hz; 485 nbt->tv_sec += leap; 486 nts.tv_sec += leap; 487 488 /* 489 * Update the time_second 'approximate time' global. 490 */ 491 time_second = nts.tv_sec; 492 } 493 494 /* 495 * Finally, our new basetime is ready to go live! 496 */ 497 cpu_sfence(); 498 basetime_index = ni; 499 500 /* 501 * Figure out how badly the system is starved for memory 502 */ 503 vm_fault_ratecheck(); 504 } 505 506 /* 507 * softticks are handled for all cpus 508 */ 509 hardclock_softtick(gd); 510 511 /* 512 * ITimer handling is per-tick, per-cpu. I don't think psignal() 513 * is mpsafe on curproc, so XXX get the mplock. 514 */ 515 if ((p = curproc) != NULL && try_mplock()) { 516 pstats = p->p_stats; 517 if (frame && CLKF_USERMODE(frame) && 518 timevalisset(&p->p_timer[ITIMER_VIRTUAL].it_value) && 519 itimerdecr(&p->p_timer[ITIMER_VIRTUAL], tick) == 0) 520 psignal(p, SIGVTALRM); 521 if (timevalisset(&p->p_timer[ITIMER_PROF].it_value) && 522 itimerdecr(&p->p_timer[ITIMER_PROF], tick) == 0) 523 psignal(p, SIGPROF); 524 rel_mplock(); 525 } 526 setdelayed(); 527 } 528 529 /* 530 * The statistics clock typically runs at a 125Hz rate, and is intended 531 * to be frequency offset from the hardclock (typ 100Hz). It is per-cpu. 532 * 533 * NOTE! systimer! the MP lock might not be held here. We can only safely 534 * manipulate objects owned by the current cpu. 535 * 536 * The stats clock is responsible for grabbing a profiling sample. 537 * Most of the statistics are only used by user-level statistics programs. 538 * The main exceptions are p->p_uticks, p->p_sticks, p->p_iticks, and 539 * p->p_estcpu. 540 * 541 * Like the other clocks, the stat clock is called from what is effectively 542 * a fast interrupt, so the context should be the thread/process that got 543 * interrupted. 544 */ 545 static void 546 statclock(systimer_t info, struct intrframe *frame) 547 { 548 #ifdef GPROF 549 struct gmonparam *g; 550 int i; 551 #endif 552 thread_t td; 553 struct proc *p; 554 int bump; 555 struct timeval tv; 556 struct timeval *stv; 557 558 /* 559 * How big was our timeslice relative to the last time? 560 */ 561 microuptime(&tv); /* mpsafe */ 562 stv = &mycpu->gd_stattv; 563 if (stv->tv_sec == 0) { 564 bump = 1; 565 } else { 566 bump = tv.tv_usec - stv->tv_usec + 567 (tv.tv_sec - stv->tv_sec) * 1000000; 568 if (bump < 0) 569 bump = 0; 570 if (bump > 1000000) 571 bump = 1000000; 572 } 573 *stv = tv; 574 575 td = curthread; 576 p = td->td_proc; 577 578 if (frame && CLKF_USERMODE(frame)) { 579 /* 580 * Came from userland, handle user time and deal with 581 * possible process. 582 */ 583 if (p && (p->p_flag & P_PROFIL)) 584 addupc_intr(p, CLKF_PC(frame), 1); 585 td->td_uticks += bump; 586 587 /* 588 * Charge the time as appropriate 589 */ 590 if (p && p->p_nice > NZERO) 591 cpu_time.cp_nice += bump; 592 else 593 cpu_time.cp_user += bump; 594 } else { 595 #ifdef GPROF 596 /* 597 * Kernel statistics are just like addupc_intr, only easier. 598 */ 599 g = &_gmonparam; 600 if (g->state == GMON_PROF_ON && frame) { 601 i = CLKF_PC(frame) - g->lowpc; 602 if (i < g->textsize) { 603 i /= HISTFRACTION * sizeof(*g->kcount); 604 g->kcount[i]++; 605 } 606 } 607 #endif 608 /* 609 * Came from kernel mode, so we were: 610 * - handling an interrupt, 611 * - doing syscall or trap work on behalf of the current 612 * user process, or 613 * - spinning in the idle loop. 614 * Whichever it is, charge the time as appropriate. 615 * Note that we charge interrupts to the current process, 616 * regardless of whether they are ``for'' that process, 617 * so that we know how much of its real time was spent 618 * in ``non-process'' (i.e., interrupt) work. 619 * 620 * XXX assume system if frame is NULL. A NULL frame 621 * can occur if ipi processing is done from a crit_exit(). 622 */ 623 if (frame && CLKF_INTR(frame)) 624 td->td_iticks += bump; 625 else 626 td->td_sticks += bump; 627 628 if (frame && CLKF_INTR(frame)) { 629 #ifdef DEBUG_PCTRACK 630 do_pctrack(frame, PCTRACK_INT); 631 #endif 632 cpu_time.cp_intr += bump; 633 } else { 634 if (td == &mycpu->gd_idlethread) { 635 cpu_time.cp_idle += bump; 636 } else { 637 #ifdef DEBUG_PCTRACK 638 if (frame) 639 do_pctrack(frame, PCTRACK_SYS); 640 #endif 641 cpu_time.cp_sys += bump; 642 } 643 } 644 } 645 } 646 647 #ifdef DEBUG_PCTRACK 648 /* 649 * Sample the PC when in the kernel or in an interrupt. User code can 650 * retrieve the information and generate a histogram or other output. 651 */ 652 653 static void 654 do_pctrack(struct intrframe *frame, int which) 655 { 656 struct kinfo_pctrack *pctrack; 657 658 pctrack = &cputime_pctrack[mycpu->gd_cpuid][which]; 659 pctrack->pc_array[pctrack->pc_index & PCTRACK_ARYMASK] = 660 (void *)CLKF_PC(frame); 661 ++pctrack->pc_index; 662 } 663 664 static int 665 sysctl_pctrack(SYSCTL_HANDLER_ARGS) 666 { 667 struct kinfo_pcheader head; 668 int error; 669 int cpu; 670 int ntrack; 671 672 head.pc_ntrack = PCTRACK_SIZE; 673 head.pc_arysize = PCTRACK_ARYSIZE; 674 675 if ((error = SYSCTL_OUT(req, &head, sizeof(head))) != 0) 676 return (error); 677 678 for (cpu = 0; cpu < ncpus; ++cpu) { 679 for (ntrack = 0; ntrack < PCTRACK_SIZE; ++ntrack) { 680 error = SYSCTL_OUT(req, &cputime_pctrack[cpu][ntrack], 681 sizeof(struct kinfo_pctrack)); 682 if (error) 683 break; 684 } 685 if (error) 686 break; 687 } 688 return (error); 689 } 690 SYSCTL_PROC(_kern, OID_AUTO, pctrack, (CTLTYPE_OPAQUE|CTLFLAG_RD), 0, 0, 691 sysctl_pctrack, "S,kinfo_pcheader", "CPU PC tracking"); 692 693 #endif 694 695 /* 696 * The scheduler clock typically runs at a 50Hz rate. NOTE! systimer, 697 * the MP lock might not be held. We can safely manipulate parts of curproc 698 * but that's about it. 699 * 700 * Each cpu has its own scheduler clock. 701 */ 702 static void 703 schedclock(systimer_t info, struct intrframe *frame) 704 { 705 struct lwp *lp; 706 struct pstats *pstats; 707 struct rusage *ru; 708 struct vmspace *vm; 709 long rss; 710 711 if ((lp = lwkt_preempted_proc()) != NULL) { 712 /* 713 * Account for cpu time used and hit the scheduler. Note 714 * that this call MUST BE MP SAFE, and the BGL IS NOT HELD 715 * HERE. 716 */ 717 ++lp->lwp_cpticks; 718 lp->lwp_proc->p_usched->schedulerclock(lp, info->periodic, 719 info->time); 720 } 721 if ((lp = curthread->td_lwp) != NULL) { 722 /* 723 * Update resource usage integrals and maximums. 724 */ 725 if ((pstats = lp->lwp_stats) != NULL && 726 (ru = &pstats->p_ru) != NULL && 727 (vm = lp->lwp_proc->p_vmspace) != NULL) { 728 ru->ru_ixrss += pgtok(vm->vm_tsize); 729 ru->ru_idrss += pgtok(vm->vm_dsize); 730 ru->ru_isrss += pgtok(vm->vm_ssize); 731 rss = pgtok(vmspace_resident_count(vm)); 732 if (ru->ru_maxrss < rss) 733 ru->ru_maxrss = rss; 734 } 735 } 736 } 737 738 /* 739 * Compute number of ticks for the specified amount of time. The 740 * return value is intended to be used in a clock interrupt timed 741 * operation and guarenteed to meet or exceed the requested time. 742 * If the representation overflows, return INT_MAX. The minimum return 743 * value is 1 ticks and the function will average the calculation up. 744 * If any value greater then 0 microseconds is supplied, a value 745 * of at least 2 will be returned to ensure that a near-term clock 746 * interrupt does not cause the timeout to occur (degenerately) early. 747 * 748 * Note that limit checks must take into account microseconds, which is 749 * done simply by using the smaller signed long maximum instead of 750 * the unsigned long maximum. 751 * 752 * If ints have 32 bits, then the maximum value for any timeout in 753 * 10ms ticks is 248 days. 754 */ 755 int 756 tvtohz_high(struct timeval *tv) 757 { 758 int ticks; 759 long sec, usec; 760 761 sec = tv->tv_sec; 762 usec = tv->tv_usec; 763 if (usec < 0) { 764 sec--; 765 usec += 1000000; 766 } 767 if (sec < 0) { 768 #ifdef DIAGNOSTIC 769 if (usec > 0) { 770 sec++; 771 usec -= 1000000; 772 } 773 printf("tvotohz: negative time difference %ld sec %ld usec\n", 774 sec, usec); 775 #endif 776 ticks = 1; 777 } else if (sec <= INT_MAX / hz) { 778 ticks = (int)(sec * hz + 779 ((u_long)usec + (tick - 1)) / tick) + 1; 780 } else { 781 ticks = INT_MAX; 782 } 783 return (ticks); 784 } 785 786 /* 787 * Compute number of ticks for the specified amount of time, erroring on 788 * the side of it being too low to ensure that sleeping the returned number 789 * of ticks will not result in a late return. 790 * 791 * The supplied timeval may not be negative and should be normalized. A 792 * return value of 0 is possible if the timeval converts to less then 793 * 1 tick. 794 * 795 * If ints have 32 bits, then the maximum value for any timeout in 796 * 10ms ticks is 248 days. 797 */ 798 int 799 tvtohz_low(struct timeval *tv) 800 { 801 int ticks; 802 long sec; 803 804 sec = tv->tv_sec; 805 if (sec <= INT_MAX / hz) 806 ticks = (int)(sec * hz + (u_long)tv->tv_usec / tick); 807 else 808 ticks = INT_MAX; 809 return (ticks); 810 } 811 812 813 /* 814 * Start profiling on a process. 815 * 816 * Kernel profiling passes proc0 which never exits and hence 817 * keeps the profile clock running constantly. 818 */ 819 void 820 startprofclock(struct proc *p) 821 { 822 if ((p->p_flag & P_PROFIL) == 0) { 823 p->p_flag |= P_PROFIL; 824 #if 0 /* XXX */ 825 if (++profprocs == 1 && stathz != 0) { 826 crit_enter(); 827 psdiv = psratio; 828 setstatclockrate(profhz); 829 crit_exit(); 830 } 831 #endif 832 } 833 } 834 835 /* 836 * Stop profiling on a process. 837 */ 838 void 839 stopprofclock(struct proc *p) 840 { 841 if (p->p_flag & P_PROFIL) { 842 p->p_flag &= ~P_PROFIL; 843 #if 0 /* XXX */ 844 if (--profprocs == 0 && stathz != 0) { 845 crit_enter(); 846 psdiv = 1; 847 setstatclockrate(stathz); 848 crit_exit(); 849 } 850 #endif 851 } 852 } 853 854 /* 855 * Return information about system clocks. 856 */ 857 static int 858 sysctl_kern_clockrate(SYSCTL_HANDLER_ARGS) 859 { 860 struct kinfo_clockinfo clkinfo; 861 /* 862 * Construct clockinfo structure. 863 */ 864 clkinfo.ci_hz = hz; 865 clkinfo.ci_tick = tick; 866 clkinfo.ci_tickadj = ntp_default_tick_delta / 1000; 867 clkinfo.ci_profhz = profhz; 868 clkinfo.ci_stathz = stathz ? stathz : hz; 869 return (sysctl_handle_opaque(oidp, &clkinfo, sizeof clkinfo, req)); 870 } 871 872 SYSCTL_PROC(_kern, KERN_CLOCKRATE, clockrate, CTLTYPE_STRUCT|CTLFLAG_RD, 873 0, 0, sysctl_kern_clockrate, "S,clockinfo",""); 874 875 /* 876 * We have eight functions for looking at the clock, four for 877 * microseconds and four for nanoseconds. For each there is fast 878 * but less precise version "get{nano|micro}[up]time" which will 879 * return a time which is up to 1/HZ previous to the call, whereas 880 * the raw version "{nano|micro}[up]time" will return a timestamp 881 * which is as precise as possible. The "up" variants return the 882 * time relative to system boot, these are well suited for time 883 * interval measurements. 884 * 885 * Each cpu independantly maintains the current time of day, so all 886 * we need to do to protect ourselves from changes is to do a loop 887 * check on the seconds field changing out from under us. 888 * 889 * The system timer maintains a 32 bit count and due to various issues 890 * it is possible for the calculated delta to occassionally exceed 891 * sys_cputimer->freq. If this occurs the sys_cputimer->freq64_nsec 892 * multiplication can easily overflow, so we deal with the case. For 893 * uniformity we deal with the case in the usec case too. 894 */ 895 void 896 getmicrouptime(struct timeval *tvp) 897 { 898 struct globaldata *gd = mycpu; 899 sysclock_t delta; 900 901 do { 902 tvp->tv_sec = gd->gd_time_seconds; 903 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base; 904 } while (tvp->tv_sec != gd->gd_time_seconds); 905 906 if (delta >= sys_cputimer->freq) { 907 tvp->tv_sec += delta / sys_cputimer->freq; 908 delta %= sys_cputimer->freq; 909 } 910 tvp->tv_usec = (sys_cputimer->freq64_usec * delta) >> 32; 911 if (tvp->tv_usec >= 1000000) { 912 tvp->tv_usec -= 1000000; 913 ++tvp->tv_sec; 914 } 915 } 916 917 void 918 getnanouptime(struct timespec *tsp) 919 { 920 struct globaldata *gd = mycpu; 921 sysclock_t delta; 922 923 do { 924 tsp->tv_sec = gd->gd_time_seconds; 925 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base; 926 } while (tsp->tv_sec != gd->gd_time_seconds); 927 928 if (delta >= sys_cputimer->freq) { 929 tsp->tv_sec += delta / sys_cputimer->freq; 930 delta %= sys_cputimer->freq; 931 } 932 tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32; 933 } 934 935 void 936 microuptime(struct timeval *tvp) 937 { 938 struct globaldata *gd = mycpu; 939 sysclock_t delta; 940 941 do { 942 tvp->tv_sec = gd->gd_time_seconds; 943 delta = sys_cputimer->count() - gd->gd_cpuclock_base; 944 } while (tvp->tv_sec != gd->gd_time_seconds); 945 946 if (delta >= sys_cputimer->freq) { 947 tvp->tv_sec += delta / sys_cputimer->freq; 948 delta %= sys_cputimer->freq; 949 } 950 tvp->tv_usec = (sys_cputimer->freq64_usec * delta) >> 32; 951 } 952 953 void 954 nanouptime(struct timespec *tsp) 955 { 956 struct globaldata *gd = mycpu; 957 sysclock_t delta; 958 959 do { 960 tsp->tv_sec = gd->gd_time_seconds; 961 delta = sys_cputimer->count() - gd->gd_cpuclock_base; 962 } while (tsp->tv_sec != gd->gd_time_seconds); 963 964 if (delta >= sys_cputimer->freq) { 965 tsp->tv_sec += delta / sys_cputimer->freq; 966 delta %= sys_cputimer->freq; 967 } 968 tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32; 969 } 970 971 /* 972 * realtime routines 973 */ 974 975 void 976 getmicrotime(struct timeval *tvp) 977 { 978 struct globaldata *gd = mycpu; 979 struct timespec *bt; 980 sysclock_t delta; 981 982 do { 983 tvp->tv_sec = gd->gd_time_seconds; 984 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base; 985 } while (tvp->tv_sec != gd->gd_time_seconds); 986 987 if (delta >= sys_cputimer->freq) { 988 tvp->tv_sec += delta / sys_cputimer->freq; 989 delta %= sys_cputimer->freq; 990 } 991 tvp->tv_usec = (sys_cputimer->freq64_usec * delta) >> 32; 992 993 bt = &basetime[basetime_index]; 994 tvp->tv_sec += bt->tv_sec; 995 tvp->tv_usec += bt->tv_nsec / 1000; 996 while (tvp->tv_usec >= 1000000) { 997 tvp->tv_usec -= 1000000; 998 ++tvp->tv_sec; 999 } 1000 } 1001 1002 void 1003 getnanotime(struct timespec *tsp) 1004 { 1005 struct globaldata *gd = mycpu; 1006 struct timespec *bt; 1007 sysclock_t delta; 1008 1009 do { 1010 tsp->tv_sec = gd->gd_time_seconds; 1011 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base; 1012 } while (tsp->tv_sec != gd->gd_time_seconds); 1013 1014 if (delta >= sys_cputimer->freq) { 1015 tsp->tv_sec += delta / sys_cputimer->freq; 1016 delta %= sys_cputimer->freq; 1017 } 1018 tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32; 1019 1020 bt = &basetime[basetime_index]; 1021 tsp->tv_sec += bt->tv_sec; 1022 tsp->tv_nsec += bt->tv_nsec; 1023 while (tsp->tv_nsec >= 1000000000) { 1024 tsp->tv_nsec -= 1000000000; 1025 ++tsp->tv_sec; 1026 } 1027 } 1028 1029 static void 1030 getnanotime_nbt(struct timespec *nbt, struct timespec *tsp) 1031 { 1032 struct globaldata *gd = mycpu; 1033 sysclock_t delta; 1034 1035 do { 1036 tsp->tv_sec = gd->gd_time_seconds; 1037 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base; 1038 } while (tsp->tv_sec != gd->gd_time_seconds); 1039 1040 if (delta >= sys_cputimer->freq) { 1041 tsp->tv_sec += delta / sys_cputimer->freq; 1042 delta %= sys_cputimer->freq; 1043 } 1044 tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32; 1045 1046 tsp->tv_sec += nbt->tv_sec; 1047 tsp->tv_nsec += nbt->tv_nsec; 1048 while (tsp->tv_nsec >= 1000000000) { 1049 tsp->tv_nsec -= 1000000000; 1050 ++tsp->tv_sec; 1051 } 1052 } 1053 1054 1055 void 1056 microtime(struct timeval *tvp) 1057 { 1058 struct globaldata *gd = mycpu; 1059 struct timespec *bt; 1060 sysclock_t delta; 1061 1062 do { 1063 tvp->tv_sec = gd->gd_time_seconds; 1064 delta = sys_cputimer->count() - gd->gd_cpuclock_base; 1065 } while (tvp->tv_sec != gd->gd_time_seconds); 1066 1067 if (delta >= sys_cputimer->freq) { 1068 tvp->tv_sec += delta / sys_cputimer->freq; 1069 delta %= sys_cputimer->freq; 1070 } 1071 tvp->tv_usec = (sys_cputimer->freq64_usec * delta) >> 32; 1072 1073 bt = &basetime[basetime_index]; 1074 tvp->tv_sec += bt->tv_sec; 1075 tvp->tv_usec += bt->tv_nsec / 1000; 1076 while (tvp->tv_usec >= 1000000) { 1077 tvp->tv_usec -= 1000000; 1078 ++tvp->tv_sec; 1079 } 1080 } 1081 1082 void 1083 nanotime(struct timespec *tsp) 1084 { 1085 struct globaldata *gd = mycpu; 1086 struct timespec *bt; 1087 sysclock_t delta; 1088 1089 do { 1090 tsp->tv_sec = gd->gd_time_seconds; 1091 delta = sys_cputimer->count() - gd->gd_cpuclock_base; 1092 } while (tsp->tv_sec != gd->gd_time_seconds); 1093 1094 if (delta >= sys_cputimer->freq) { 1095 tsp->tv_sec += delta / sys_cputimer->freq; 1096 delta %= sys_cputimer->freq; 1097 } 1098 tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32; 1099 1100 bt = &basetime[basetime_index]; 1101 tsp->tv_sec += bt->tv_sec; 1102 tsp->tv_nsec += bt->tv_nsec; 1103 while (tsp->tv_nsec >= 1000000000) { 1104 tsp->tv_nsec -= 1000000000; 1105 ++tsp->tv_sec; 1106 } 1107 } 1108 1109 /* 1110 * note: this is not exactly synchronized with real time. To do that we 1111 * would have to do what microtime does and check for a nanoseconds overflow. 1112 */ 1113 time_t 1114 get_approximate_time_t(void) 1115 { 1116 struct globaldata *gd = mycpu; 1117 struct timespec *bt; 1118 1119 bt = &basetime[basetime_index]; 1120 return(gd->gd_time_seconds + bt->tv_sec); 1121 } 1122 1123 int 1124 pps_ioctl(u_long cmd, caddr_t data, struct pps_state *pps) 1125 { 1126 pps_params_t *app; 1127 struct pps_fetch_args *fapi; 1128 #ifdef PPS_SYNC 1129 struct pps_kcbind_args *kapi; 1130 #endif 1131 1132 switch (cmd) { 1133 case PPS_IOC_CREATE: 1134 return (0); 1135 case PPS_IOC_DESTROY: 1136 return (0); 1137 case PPS_IOC_SETPARAMS: 1138 app = (pps_params_t *)data; 1139 if (app->mode & ~pps->ppscap) 1140 return (EINVAL); 1141 pps->ppsparam = *app; 1142 return (0); 1143 case PPS_IOC_GETPARAMS: 1144 app = (pps_params_t *)data; 1145 *app = pps->ppsparam; 1146 app->api_version = PPS_API_VERS_1; 1147 return (0); 1148 case PPS_IOC_GETCAP: 1149 *(int*)data = pps->ppscap; 1150 return (0); 1151 case PPS_IOC_FETCH: 1152 fapi = (struct pps_fetch_args *)data; 1153 if (fapi->tsformat && fapi->tsformat != PPS_TSFMT_TSPEC) 1154 return (EINVAL); 1155 if (fapi->timeout.tv_sec || fapi->timeout.tv_nsec) 1156 return (EOPNOTSUPP); 1157 pps->ppsinfo.current_mode = pps->ppsparam.mode; 1158 fapi->pps_info_buf = pps->ppsinfo; 1159 return (0); 1160 case PPS_IOC_KCBIND: 1161 #ifdef PPS_SYNC 1162 kapi = (struct pps_kcbind_args *)data; 1163 /* XXX Only root should be able to do this */ 1164 if (kapi->tsformat && kapi->tsformat != PPS_TSFMT_TSPEC) 1165 return (EINVAL); 1166 if (kapi->kernel_consumer != PPS_KC_HARDPPS) 1167 return (EINVAL); 1168 if (kapi->edge & ~pps->ppscap) 1169 return (EINVAL); 1170 pps->kcmode = kapi->edge; 1171 return (0); 1172 #else 1173 return (EOPNOTSUPP); 1174 #endif 1175 default: 1176 return (ENOTTY); 1177 } 1178 } 1179 1180 void 1181 pps_init(struct pps_state *pps) 1182 { 1183 pps->ppscap |= PPS_TSFMT_TSPEC; 1184 if (pps->ppscap & PPS_CAPTUREASSERT) 1185 pps->ppscap |= PPS_OFFSETASSERT; 1186 if (pps->ppscap & PPS_CAPTURECLEAR) 1187 pps->ppscap |= PPS_OFFSETCLEAR; 1188 } 1189 1190 void 1191 pps_event(struct pps_state *pps, sysclock_t count, int event) 1192 { 1193 struct globaldata *gd; 1194 struct timespec *tsp; 1195 struct timespec *osp; 1196 struct timespec *bt; 1197 struct timespec ts; 1198 sysclock_t *pcount; 1199 #ifdef PPS_SYNC 1200 sysclock_t tcount; 1201 #endif 1202 sysclock_t delta; 1203 pps_seq_t *pseq; 1204 int foff; 1205 int fhard; 1206 1207 gd = mycpu; 1208 1209 /* Things would be easier with arrays... */ 1210 if (event == PPS_CAPTUREASSERT) { 1211 tsp = &pps->ppsinfo.assert_timestamp; 1212 osp = &pps->ppsparam.assert_offset; 1213 foff = pps->ppsparam.mode & PPS_OFFSETASSERT; 1214 fhard = pps->kcmode & PPS_CAPTUREASSERT; 1215 pcount = &pps->ppscount[0]; 1216 pseq = &pps->ppsinfo.assert_sequence; 1217 } else { 1218 tsp = &pps->ppsinfo.clear_timestamp; 1219 osp = &pps->ppsparam.clear_offset; 1220 foff = pps->ppsparam.mode & PPS_OFFSETCLEAR; 1221 fhard = pps->kcmode & PPS_CAPTURECLEAR; 1222 pcount = &pps->ppscount[1]; 1223 pseq = &pps->ppsinfo.clear_sequence; 1224 } 1225 1226 /* Nothing really happened */ 1227 if (*pcount == count) 1228 return; 1229 1230 *pcount = count; 1231 1232 do { 1233 ts.tv_sec = gd->gd_time_seconds; 1234 delta = count - gd->gd_cpuclock_base; 1235 } while (ts.tv_sec != gd->gd_time_seconds); 1236 1237 if (delta >= sys_cputimer->freq) { 1238 ts.tv_sec += delta / sys_cputimer->freq; 1239 delta %= sys_cputimer->freq; 1240 } 1241 ts.tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32; 1242 bt = &basetime[basetime_index]; 1243 ts.tv_sec += bt->tv_sec; 1244 ts.tv_nsec += bt->tv_nsec; 1245 while (ts.tv_nsec >= 1000000000) { 1246 ts.tv_nsec -= 1000000000; 1247 ++ts.tv_sec; 1248 } 1249 1250 (*pseq)++; 1251 *tsp = ts; 1252 1253 if (foff) { 1254 timespecadd(tsp, osp); 1255 if (tsp->tv_nsec < 0) { 1256 tsp->tv_nsec += 1000000000; 1257 tsp->tv_sec -= 1; 1258 } 1259 } 1260 #ifdef PPS_SYNC 1261 if (fhard) { 1262 /* magic, at its best... */ 1263 tcount = count - pps->ppscount[2]; 1264 pps->ppscount[2] = count; 1265 if (tcount >= sys_cputimer->freq) { 1266 delta = (1000000000 * (tcount / sys_cputimer->freq) + 1267 sys_cputimer->freq64_nsec * 1268 (tcount % sys_cputimer->freq)) >> 32; 1269 } else { 1270 delta = (sys_cputimer->freq64_nsec * tcount) >> 32; 1271 } 1272 hardpps(tsp, delta); 1273 } 1274 #endif 1275 } 1276 1277