kern_timeout.c revision 18855
1/*- 2 * Copyright (c) 1982, 1986, 1991, 1993 3 * The Regents of the University of California. All rights reserved. 4 * (c) UNIX System Laboratories, Inc. 5 * All or some portions of this file are derived from material licensed 6 * to the University of California by American Telephone and Telegraph 7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with 8 * the permission of UNIX System Laboratories, Inc. 9 * 10 * Redistribution and use in source and binary forms, with or without 11 * modification, are permitted provided that the following conditions 12 * are met: 13 * 1. Redistributions of source code must retain the above copyright 14 * notice, this list of conditions and the following disclaimer. 15 * 2. Redistributions in binary form must reproduce the above copyright 16 * notice, this list of conditions and the following disclaimer in the 17 * documentation and/or other materials provided with the distribution. 18 * 3. All advertising materials mentioning features or use of this software 19 * must display the following acknowledgement: 20 * This product includes software developed by the University of 21 * California, Berkeley and its contributors. 22 * 4. Neither the name of the University nor the names of its contributors 23 * may be used to endorse or promote products derived from this software 24 * without specific prior written permission. 25 * 26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 36 * SUCH DAMAGE. 37 * 38 * @(#)kern_clock.c 8.5 (Berkeley) 1/21/94 39 * $Id: kern_clock.c,v 1.26 1996/07/30 16:59:22 bde Exp $ 40 */ 41 42/* Portions of this software are covered by the following: */ 43/****************************************************************************** 44 * * 45 * Copyright (c) David L. Mills 1993, 1994 * 46 * * 47 * Permission to use, copy, modify, and distribute this software and its * 48 * documentation for any purpose and without fee is hereby granted, provided * 49 * that the above copyright notice appears in all copies and that both the * 50 * copyright notice and this permission notice appear in supporting * 51 * documentation, and that the name University of Delaware not be used in * 52 * advertising or publicity pertaining to distribution of the software * 53 * without specific, written prior permission. The University of Delaware * 54 * makes no representations about the suitability this software for any * 55 * purpose. It is provided "as is" without express or implied warranty. * 56 * * 57 *****************************************************************************/ 58 59#include "opt_cpu.h" /* XXX */ 60 61#include <sys/param.h> 62#include <sys/systm.h> 63#include <sys/dkstat.h> 64#include <sys/callout.h> 65#include <sys/kernel.h> 66#include <sys/proc.h> 67#include <sys/resourcevar.h> 68#include <sys/signalvar.h> 69#include <sys/timex.h> 70#include <vm/vm.h> 71#include <vm/vm_param.h> 72#include <vm/vm_prot.h> 73#include <vm/lock.h> 74#include <vm/pmap.h> 75#include <vm/vm_map.h> 76#include <sys/sysctl.h> 77 78#include <machine/cpu.h> 79#include <machine/clock.h> 80 81#ifdef GPROF 82#include <sys/gmon.h> 83#endif 84 85static void initclocks __P((void *dummy)); 86SYSINIT(clocks, SI_SUB_CLOCKS, SI_ORDER_FIRST, initclocks, NULL) 87 88/* Exported to machdep.c. */ 89struct callout *callfree, *callout; 90 91static struct callout calltodo; 92 93/* Some of these don't belong here, but it's easiest to concentrate them. */ 94static long cp_time[CPUSTATES]; 95long dk_seek[DK_NDRIVE]; 96static long dk_time[DK_NDRIVE]; 97long dk_wds[DK_NDRIVE]; 98long dk_wpms[DK_NDRIVE]; 99long dk_xfer[DK_NDRIVE]; 100 101int dk_busy; 102int dk_ndrive = 0; 103char dk_names[DK_NDRIVE][DK_NAMELEN]; 104 105long tk_cancc; 106long tk_nin; 107long tk_nout; 108long tk_rawcc; 109 110/* 111 * Clock handling routines. 112 * 113 * This code is written to operate with two timers that run independently of 114 * each other. The main clock, running hz times per second, is used to keep 115 * track of real time. The second timer handles kernel and user profiling, 116 * and does resource use estimation. If the second timer is programmable, 117 * it is randomized to avoid aliasing between the two clocks. For example, 118 * the randomization prevents an adversary from always giving up the cpu 119 * just before its quantum expires. Otherwise, it would never accumulate 120 * cpu ticks. The mean frequency of the second timer is stathz. 121 * 122 * If no second timer exists, stathz will be zero; in this case we drive 123 * profiling and statistics off the main clock. This WILL NOT be accurate; 124 * do not do it unless absolutely necessary. 125 * 126 * The statistics clock may (or may not) be run at a higher rate while 127 * profiling. This profile clock runs at profhz. We require that profhz 128 * be an integral multiple of stathz. 129 * 130 * If the statistics clock is running fast, it must be divided by the ratio 131 * profhz/stathz for statistics. (For profiling, every tick counts.) 132 */ 133 134/* 135 * TODO: 136 * allocate more timeout table slots when table overflows. 137 */ 138 139/* 140 * Bump a timeval by a small number of usec's. 141 */ 142#define BUMPTIME(t, usec) { \ 143 register volatile struct timeval *tp = (t); \ 144 register long us; \ 145 \ 146 tp->tv_usec = us = tp->tv_usec + (usec); \ 147 if (us >= 1000000) { \ 148 tp->tv_usec = us - 1000000; \ 149 tp->tv_sec++; \ 150 } \ 151} 152 153int stathz; 154int profhz; 155static int profprocs; 156int ticks; 157static int psdiv, pscnt; /* prof => stat divider */ 158int psratio; /* ratio: prof / stat */ 159 160volatile struct timeval time; 161volatile struct timeval mono_time; 162 163/* 164 * Phase-lock loop (PLL) definitions 165 * 166 * The following variables are read and set by the ntp_adjtime() system 167 * call. 168 * 169 * time_state shows the state of the system clock, with values defined 170 * in the timex.h header file. 171 * 172 * time_status shows the status of the system clock, with bits defined 173 * in the timex.h header file. 174 * 175 * time_offset is used by the PLL to adjust the system time in small 176 * increments. 177 * 178 * time_constant determines the bandwidth or "stiffness" of the PLL. 179 * 180 * time_tolerance determines maximum frequency error or tolerance of the 181 * CPU clock oscillator and is a property of the architecture; however, 182 * in principle it could change as result of the presence of external 183 * discipline signals, for instance. 184 * 185 * time_precision is usually equal to the kernel tick variable; however, 186 * in cases where a precision clock counter or external clock is 187 * available, the resolution can be much less than this and depend on 188 * whether the external clock is working or not. 189 * 190 * time_maxerror is initialized by a ntp_adjtime() call and increased by 191 * the kernel once each second to reflect the maximum error 192 * bound growth. 193 * 194 * time_esterror is set and read by the ntp_adjtime() call, but 195 * otherwise not used by the kernel. 196 */ 197int time_status = STA_UNSYNC; /* clock status bits */ 198int time_state = TIME_OK; /* clock state */ 199long time_offset = 0; /* time offset (us) */ 200long time_constant = 0; /* pll time constant */ 201long time_tolerance = MAXFREQ; /* frequency tolerance (scaled ppm) */ 202long time_precision = 1; /* clock precision (us) */ 203long time_maxerror = MAXPHASE; /* maximum error (us) */ 204long time_esterror = MAXPHASE; /* estimated error (us) */ 205 206/* 207 * The following variables establish the state of the PLL and the 208 * residual time and frequency offset of the local clock. The scale 209 * factors are defined in the timex.h header file. 210 * 211 * time_phase and time_freq are the phase increment and the frequency 212 * increment, respectively, of the kernel time variable at each tick of 213 * the clock. 214 * 215 * time_freq is set via ntp_adjtime() from a value stored in a file when 216 * the synchronization daemon is first started. Its value is retrieved 217 * via ntp_adjtime() and written to the file about once per hour by the 218 * daemon. 219 * 220 * time_adj is the adjustment added to the value of tick at each timer 221 * interrupt and is recomputed at each timer interrupt. 222 * 223 * time_reftime is the second's portion of the system time on the last 224 * call to ntp_adjtime(). It is used to adjust the time_freq variable 225 * and to increase the time_maxerror as the time since last update 226 * increases. 227 */ 228static long time_phase = 0; /* phase offset (scaled us) */ 229long time_freq = 0; /* frequency offset (scaled ppm) */ 230static long time_adj = 0; /* tick adjust (scaled 1 / hz) */ 231static long time_reftime = 0; /* time at last adjustment (s) */ 232 233#ifdef PPS_SYNC 234/* 235 * The following variables are used only if the if the kernel PPS 236 * discipline code is configured (PPS_SYNC). The scale factors are 237 * defined in the timex.h header file. 238 * 239 * pps_time contains the time at each calibration interval, as read by 240 * microtime(). 241 * 242 * pps_offset is the time offset produced by the time median filter 243 * pps_tf[], while pps_jitter is the dispersion measured by this 244 * filter. 245 * 246 * pps_freq is the frequency offset produced by the frequency median 247 * filter pps_ff[], while pps_stabil is the dispersion measured by 248 * this filter. 249 * 250 * pps_usec is latched from a high resolution counter or external clock 251 * at pps_time. Here we want the hardware counter contents only, not the 252 * contents plus the time_tv.usec as usual. 253 * 254 * pps_valid counts the number of seconds since the last PPS update. It 255 * is used as a watchdog timer to disable the PPS discipline should the 256 * PPS signal be lost. 257 * 258 * pps_glitch counts the number of seconds since the beginning of an 259 * offset burst more than tick/2 from current nominal offset. It is used 260 * mainly to suppress error bursts due to priority conflicts between the 261 * PPS interrupt and timer interrupt. 262 * 263 * pps_count counts the seconds of the calibration interval, the 264 * duration of which is pps_shift in powers of two. 265 * 266 * pps_intcnt counts the calibration intervals for use in the interval- 267 * adaptation algorithm. It's just too complicated for words. 268 */ 269struct timeval pps_time; /* kernel time at last interval */ 270long pps_offset = 0; /* pps time offset (us) */ 271long pps_jitter = MAXTIME; /* pps time dispersion (jitter) (us) */ 272long pps_tf[] = {0, 0, 0}; /* pps time offset median filter (us) */ 273long pps_freq = 0; /* frequency offset (scaled ppm) */ 274long pps_stabil = MAXFREQ; /* frequency dispersion (scaled ppm) */ 275long pps_ff[] = {0, 0, 0}; /* frequency offset median filter */ 276long pps_usec = 0; /* microsec counter at last interval */ 277long pps_valid = PPS_VALID; /* pps signal watchdog counter */ 278int pps_glitch = 0; /* pps signal glitch counter */ 279int pps_count = 0; /* calibration interval counter (s) */ 280int pps_shift = PPS_SHIFT; /* interval duration (s) (shift) */ 281int pps_intcnt = 0; /* intervals at current duration */ 282 283/* 284 * PPS signal quality monitors 285 * 286 * pps_jitcnt counts the seconds that have been discarded because the 287 * jitter measured by the time median filter exceeds the limit MAXTIME 288 * (100 us). 289 * 290 * pps_calcnt counts the frequency calibration intervals, which are 291 * variable from 4 s to 256 s. 292 * 293 * pps_errcnt counts the calibration intervals which have been discarded 294 * because the wander exceeds the limit MAXFREQ (100 ppm) or where the 295 * calibration interval jitter exceeds two ticks. 296 * 297 * pps_stbcnt counts the calibration intervals that have been discarded 298 * because the frequency wander exceeds the limit MAXFREQ / 4 (25 us). 299 */ 300long pps_jitcnt = 0; /* jitter limit exceeded */ 301long pps_calcnt = 0; /* calibration intervals */ 302long pps_errcnt = 0; /* calibration errors */ 303long pps_stbcnt = 0; /* stability limit exceeded */ 304#endif /* PPS_SYNC */ 305 306/* XXX none of this stuff works under FreeBSD */ 307#ifdef EXT_CLOCK 308/* 309 * External clock definitions 310 * 311 * The following definitions and declarations are used only if an 312 * external clock (HIGHBALL or TPRO) is configured on the system. 313 */ 314#define CLOCK_INTERVAL 30 /* CPU clock update interval (s) */ 315 316/* 317 * The clock_count variable is set to CLOCK_INTERVAL at each PPS 318 * interrupt and decremented once each second. 319 */ 320int clock_count = 0; /* CPU clock counter */ 321 322#ifdef HIGHBALL 323/* 324 * The clock_offset and clock_cpu variables are used by the HIGHBALL 325 * interface. The clock_offset variable defines the offset between 326 * system time and the HIGBALL counters. The clock_cpu variable contains 327 * the offset between the system clock and the HIGHBALL clock for use in 328 * disciplining the kernel time variable. 329 */ 330extern struct timeval clock_offset; /* Highball clock offset */ 331long clock_cpu = 0; /* CPU clock adjust */ 332#endif /* HIGHBALL */ 333#endif /* EXT_CLOCK */ 334 335/* 336 * hardupdate() - local clock update 337 * 338 * This routine is called by ntp_adjtime() to update the local clock 339 * phase and frequency. This is used to implement an adaptive-parameter, 340 * first-order, type-II phase-lock loop. The code computes new time and 341 * frequency offsets each time it is called. The hardclock() routine 342 * amortizes these offsets at each tick interrupt. If the kernel PPS 343 * discipline code is configured (PPS_SYNC), the PPS signal itself 344 * determines the new time offset, instead of the calling argument. 345 * Presumably, calls to ntp_adjtime() occur only when the caller 346 * believes the local clock is valid within some bound (+-128 ms with 347 * NTP). If the caller's time is far different than the PPS time, an 348 * argument will ensue, and it's not clear who will lose. 349 * 350 * For default SHIFT_UPDATE = 12, the offset is limited to +-512 ms, the 351 * maximum interval between updates is 4096 s and the maximum frequency 352 * offset is +-31.25 ms/s. 353 * 354 * Note: splclock() is in effect. 355 */ 356void 357hardupdate(offset) 358 long offset; 359{ 360 long ltemp, mtemp; 361 362 if (!(time_status & STA_PLL) && !(time_status & STA_PPSTIME)) 363 return; 364 ltemp = offset; 365#ifdef PPS_SYNC 366 if (time_status & STA_PPSTIME && time_status & STA_PPSSIGNAL) 367 ltemp = pps_offset; 368#endif /* PPS_SYNC */ 369 if (ltemp > MAXPHASE) 370 time_offset = MAXPHASE << SHIFT_UPDATE; 371 else if (ltemp < -MAXPHASE) 372 time_offset = -(MAXPHASE << SHIFT_UPDATE); 373 else 374 time_offset = ltemp << SHIFT_UPDATE; 375 mtemp = time.tv_sec - time_reftime; 376 time_reftime = time.tv_sec; 377 if (mtemp > MAXSEC) 378 mtemp = 0; 379 380 /* ugly multiply should be replaced */ 381 if (ltemp < 0) 382 time_freq -= (-ltemp * mtemp) >> (time_constant + 383 time_constant + SHIFT_KF - SHIFT_USEC); 384 else 385 time_freq += (ltemp * mtemp) >> (time_constant + 386 time_constant + SHIFT_KF - SHIFT_USEC); 387 if (time_freq > time_tolerance) 388 time_freq = time_tolerance; 389 else if (time_freq < -time_tolerance) 390 time_freq = -time_tolerance; 391} 392 393 394 395/* 396 * Initialize clock frequencies and start both clocks running. 397 */ 398/* ARGSUSED*/ 399static void 400initclocks(dummy) 401 void *dummy; 402{ 403 register int i; 404 405 /* 406 * Set divisors to 1 (normal case) and let the machine-specific 407 * code do its bit. 408 */ 409 psdiv = pscnt = 1; 410 cpu_initclocks(); 411 412 /* 413 * Compute profhz/stathz, and fix profhz if needed. 414 */ 415 i = stathz ? stathz : hz; 416 if (profhz == 0) 417 profhz = i; 418 psratio = profhz / i; 419} 420 421/* 422 * The real-time timer, interrupting hz times per second. 423 */ 424void 425hardclock(frame) 426 register struct clockframe *frame; 427{ 428 register struct callout *p1; 429 register struct proc *p; 430 register int needsoft; 431 432 /* 433 * Update real-time timeout queue. 434 * At front of queue are some number of events which are ``due''. 435 * The time to these is <= 0 and if negative represents the 436 * number of ticks which have passed since it was supposed to happen. 437 * The rest of the q elements (times > 0) are events yet to happen, 438 * where the time for each is given as a delta from the previous. 439 * Decrementing just the first of these serves to decrement the time 440 * to all events. 441 */ 442 needsoft = 0; 443 for (p1 = calltodo.c_next; p1 != NULL; p1 = p1->c_next) { 444 if (--p1->c_time > 0) 445 break; 446 needsoft = 1; 447 if (p1->c_time == 0) 448 break; 449 } 450 451 p = curproc; 452 if (p) { 453 register struct pstats *pstats; 454 455 /* 456 * Run current process's virtual and profile time, as needed. 457 */ 458 pstats = p->p_stats; 459 if (CLKF_USERMODE(frame) && 460 timerisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) && 461 itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0) 462 psignal(p, SIGVTALRM); 463 if (timerisset(&pstats->p_timer[ITIMER_PROF].it_value) && 464 itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0) 465 psignal(p, SIGPROF); 466 } 467 468 /* 469 * If no separate statistics clock is available, run it from here. 470 */ 471 if (stathz == 0) 472 statclock(frame); 473 474 /* 475 * Increment the time-of-day. 476 */ 477 ticks++; 478 { 479 int time_update; 480 struct timeval newtime = time; 481 long ltemp; 482 483 if (timedelta == 0) { 484 time_update = CPU_THISTICKLEN(tick); 485 } else { 486 time_update = CPU_THISTICKLEN(tick) + tickdelta; 487 timedelta -= tickdelta; 488 } 489 BUMPTIME(&mono_time, time_update); 490 491 /* 492 * Compute the phase adjustment. If the low-order bits 493 * (time_phase) of the update overflow, bump the high-order bits 494 * (time_update). 495 */ 496 time_phase += time_adj; 497 if (time_phase <= -FINEUSEC) { 498 ltemp = -time_phase >> SHIFT_SCALE; 499 time_phase += ltemp << SHIFT_SCALE; 500 time_update -= ltemp; 501 } 502 else if (time_phase >= FINEUSEC) { 503 ltemp = time_phase >> SHIFT_SCALE; 504 time_phase -= ltemp << SHIFT_SCALE; 505 time_update += ltemp; 506 } 507 508 newtime.tv_usec += time_update; 509 /* 510 * On rollover of the second the phase adjustment to be used for 511 * the next second is calculated. Also, the maximum error is 512 * increased by the tolerance. If the PPS frequency discipline 513 * code is present, the phase is increased to compensate for the 514 * CPU clock oscillator frequency error. 515 * 516 * With SHIFT_SCALE = 23, the maximum frequency adjustment is 517 * +-256 us per tick, or 25.6 ms/s at a clock frequency of 100 518 * Hz. The time contribution is shifted right a minimum of two 519 * bits, while the frequency contribution is a right shift. 520 * Thus, overflow is prevented if the frequency contribution is 521 * limited to half the maximum or 15.625 ms/s. 522 */ 523 if (newtime.tv_usec >= 1000000) { 524 newtime.tv_usec -= 1000000; 525 newtime.tv_sec++; 526 time_maxerror += time_tolerance >> SHIFT_USEC; 527 if (time_offset < 0) { 528 ltemp = -time_offset >> 529 (SHIFT_KG + time_constant); 530 time_offset += ltemp; 531 time_adj = -ltemp << 532 (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE); 533 } else { 534 ltemp = time_offset >> 535 (SHIFT_KG + time_constant); 536 time_offset -= ltemp; 537 time_adj = ltemp << 538 (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE); 539 } 540#ifdef PPS_SYNC 541 /* 542 * Gnaw on the watchdog counter and update the frequency 543 * computed by the pll and the PPS signal. 544 */ 545 pps_valid++; 546 if (pps_valid == PPS_VALID) { 547 pps_jitter = MAXTIME; 548 pps_stabil = MAXFREQ; 549 time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER | 550 STA_PPSWANDER | STA_PPSERROR); 551 } 552 ltemp = time_freq + pps_freq; 553#else 554 ltemp = time_freq; 555#endif /* PPS_SYNC */ 556 if (ltemp < 0) 557 time_adj -= -ltemp >> 558 (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE); 559 else 560 time_adj += ltemp >> 561 (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE); 562 563 /* 564 * When the CPU clock oscillator frequency is not a 565 * power of two in Hz, the SHIFT_HZ is only an 566 * approximate scale factor. In the SunOS kernel, this 567 * results in a PLL gain factor of 1/1.28 = 0.78 what it 568 * should be. In the following code the overall gain is 569 * increased by a factor of 1.25, which results in a 570 * residual error less than 3 percent. 571 */ 572 /* Same thing applies for FreeBSD --GAW */ 573 if (hz == 100) { 574 if (time_adj < 0) 575 time_adj -= -time_adj >> 2; 576 else 577 time_adj += time_adj >> 2; 578 } 579 580 /* XXX - this is really bogus, but can't be fixed until 581 xntpd's idea of the system clock is fixed to know how 582 the user wants leap seconds handled; in the mean time, 583 we assume that users of NTP are running without proper 584 leap second support (this is now the default anyway) */ 585 /* 586 * Leap second processing. If in leap-insert state at 587 * the end of the day, the system clock is set back one 588 * second; if in leap-delete state, the system clock is 589 * set ahead one second. The microtime() routine or 590 * external clock driver will insure that reported time 591 * is always monotonic. The ugly divides should be 592 * replaced. 593 */ 594 switch (time_state) { 595 596 case TIME_OK: 597 if (time_status & STA_INS) 598 time_state = TIME_INS; 599 else if (time_status & STA_DEL) 600 time_state = TIME_DEL; 601 break; 602 603 case TIME_INS: 604 if (newtime.tv_sec % 86400 == 0) { 605 newtime.tv_sec--; 606 time_state = TIME_OOP; 607 } 608 break; 609 610 case TIME_DEL: 611 if ((newtime.tv_sec + 1) % 86400 == 0) { 612 newtime.tv_sec++; 613 time_state = TIME_WAIT; 614 } 615 break; 616 617 case TIME_OOP: 618 time_state = TIME_WAIT; 619 break; 620 621 case TIME_WAIT: 622 if (!(time_status & (STA_INS | STA_DEL))) 623 time_state = TIME_OK; 624 } 625 } 626 CPU_CLOCKUPDATE(&time, &newtime); 627 } 628 629 /* 630 * Process callouts at a very low cpu priority, so we don't keep the 631 * relatively high clock interrupt priority any longer than necessary. 632 */ 633 if (needsoft) { 634 if (CLKF_BASEPRI(frame)) { 635 /* 636 * Save the overhead of a software interrupt; 637 * it will happen as soon as we return, so do it now. 638 */ 639 (void)splsoftclock(); 640 softclock(); 641 } else 642 setsoftclock(); 643 } 644} 645 646/* 647 * Software (low priority) clock interrupt. 648 * Run periodic events from timeout queue. 649 */ 650/*ARGSUSED*/ 651void 652softclock() 653{ 654 register struct callout *c; 655 register void *arg; 656 register void (*func) __P((void *)); 657 register int s; 658 659 s = splhigh(); 660 while ((c = calltodo.c_next) != NULL && c->c_time <= 0) { 661 func = c->c_func; 662 arg = c->c_arg; 663 calltodo.c_next = c->c_next; 664 c->c_next = callfree; 665 callfree = c; 666 splx(s); 667 (*func)(arg); 668 (void) splhigh(); 669 } 670 splx(s); 671} 672 673/* 674 * timeout -- 675 * Execute a function after a specified length of time. 676 * 677 * untimeout -- 678 * Cancel previous timeout function call. 679 * 680 * See AT&T BCI Driver Reference Manual for specification. This 681 * implementation differs from that one in that no identification 682 * value is returned from timeout, rather, the original arguments 683 * to timeout are used to identify entries for untimeout. 684 */ 685void 686timeout(ftn, arg, ticks) 687 timeout_t ftn; 688 void *arg; 689 register int ticks; 690{ 691 register struct callout *new, *p, *t; 692 register int s; 693 694 if (ticks <= 0) 695 ticks = 1; 696 697 /* Lock out the clock. */ 698 s = splhigh(); 699 700 /* Fill in the next free callout structure. */ 701 if (callfree == NULL) 702 panic("timeout table full"); 703 new = callfree; 704 callfree = new->c_next; 705 new->c_arg = arg; 706 new->c_func = ftn; 707 708 /* 709 * The time for each event is stored as a difference from the time 710 * of the previous event on the queue. Walk the queue, correcting 711 * the ticks argument for queue entries passed. Correct the ticks 712 * value for the queue entry immediately after the insertion point 713 * as well. Watch out for negative c_time values; these represent 714 * overdue events. 715 */ 716 for (p = &calltodo; 717 (t = p->c_next) != NULL && ticks > t->c_time; p = t) 718 if (t->c_time > 0) 719 ticks -= t->c_time; 720 new->c_time = ticks; 721 if (t != NULL) 722 t->c_time -= ticks; 723 724 /* Insert the new entry into the queue. */ 725 p->c_next = new; 726 new->c_next = t; 727 splx(s); 728} 729 730void 731untimeout(ftn, arg) 732 timeout_t ftn; 733 void *arg; 734{ 735 register struct callout *p, *t; 736 register int s; 737 738 s = splhigh(); 739 for (p = &calltodo; (t = p->c_next) != NULL; p = t) 740 if (t->c_func == ftn && t->c_arg == arg) { 741 /* Increment next entry's tick count. */ 742 if (t->c_next && t->c_time > 0) 743 t->c_next->c_time += t->c_time; 744 745 /* Move entry from callout queue to callfree queue. */ 746 p->c_next = t->c_next; 747 t->c_next = callfree; 748 callfree = t; 749 break; 750 } 751 splx(s); 752} 753 754/* 755 * Compute number of hz until specified time. Used to 756 * compute third argument to timeout() from an absolute time. 757 */ 758int 759hzto(tv) 760 struct timeval *tv; 761{ 762 register unsigned long ticks; 763 register long sec, usec; 764 int s; 765 766 /* 767 * If the number of usecs in the whole seconds part of the time 768 * difference fits in a long, then the total number of usecs will 769 * fit in an unsigned long. Compute the total and convert it to 770 * ticks, rounding up and adding 1 to allow for the current tick 771 * to expire. Rounding also depends on unsigned long arithmetic 772 * to avoid overflow. 773 * 774 * Otherwise, if the number of ticks in the whole seconds part of 775 * the time difference fits in a long, then convert the parts to 776 * ticks separately and add, using similar rounding methods and 777 * overflow avoidance. This method would work in the previous 778 * case but it is slightly slower and assumes that hz is integral. 779 * 780 * Otherwise, round the time difference down to the maximum 781 * representable value. 782 * 783 * If ints have 32 bits, then the maximum value for any timeout in 784 * 10ms ticks is 248 days. 785 */ 786 s = splclock(); 787 sec = tv->tv_sec - time.tv_sec; 788 usec = tv->tv_usec - time.tv_usec; 789 splx(s); 790 if (usec < 0) { 791 sec--; 792 usec += 1000000; 793 } 794 if (sec < 0) { 795#ifdef DIAGNOSTIC 796 printf("hzto: negative time difference %ld sec %ld usec\n", 797 sec, usec); 798#endif 799 ticks = 1; 800 } else if (sec <= LONG_MAX / 1000000) 801 ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1)) 802 / tick + 1; 803 else if (sec <= LONG_MAX / hz) 804 ticks = sec * hz 805 + ((unsigned long)usec + (tick - 1)) / tick + 1; 806 else 807 ticks = LONG_MAX; 808 if (ticks > INT_MAX) 809 ticks = INT_MAX; 810 return (ticks); 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 */ 819void 820startprofclock(p) 821 register struct proc *p; 822{ 823 int s; 824 825 if ((p->p_flag & P_PROFIL) == 0) { 826 p->p_flag |= P_PROFIL; 827 if (++profprocs == 1 && stathz != 0) { 828 s = splstatclock(); 829 psdiv = pscnt = psratio; 830 setstatclockrate(profhz); 831 splx(s); 832 } 833 } 834} 835 836/* 837 * Stop profiling on a process. 838 */ 839void 840stopprofclock(p) 841 register struct proc *p; 842{ 843 int s; 844 845 if (p->p_flag & P_PROFIL) { 846 p->p_flag &= ~P_PROFIL; 847 if (--profprocs == 0 && stathz != 0) { 848 s = splstatclock(); 849 psdiv = pscnt = 1; 850 setstatclockrate(stathz); 851 splx(s); 852 } 853 } 854} 855 856/* 857 * Statistics clock. Grab profile sample, and if divider reaches 0, 858 * do process and kernel statistics. 859 */ 860void 861statclock(frame) 862 register struct clockframe *frame; 863{ 864#ifdef GPROF 865 register struct gmonparam *g; 866#endif 867 register struct proc *p; 868 register int i; 869 struct pstats *pstats; 870 long rss; 871 struct rusage *ru; 872 struct vmspace *vm; 873 874 if (CLKF_USERMODE(frame)) { 875 p = curproc; 876 if (p->p_flag & P_PROFIL) 877 addupc_intr(p, CLKF_PC(frame), 1); 878 if (--pscnt > 0) 879 return; 880 /* 881 * Came from user mode; CPU was in user state. 882 * If this process is being profiled record the tick. 883 */ 884 p->p_uticks++; 885 if (p->p_nice > NZERO) 886 cp_time[CP_NICE]++; 887 else 888 cp_time[CP_USER]++; 889 } else { 890#ifdef GPROF 891 /* 892 * Kernel statistics are just like addupc_intr, only easier. 893 */ 894 g = &_gmonparam; 895 if (g->state == GMON_PROF_ON) { 896 i = CLKF_PC(frame) - g->lowpc; 897 if (i < g->textsize) { 898 i /= HISTFRACTION * sizeof(*g->kcount); 899 g->kcount[i]++; 900 } 901 } 902#endif 903 if (--pscnt > 0) 904 return; 905 /* 906 * Came from kernel mode, so we were: 907 * - handling an interrupt, 908 * - doing syscall or trap work on behalf of the current 909 * user process, or 910 * - spinning in the idle loop. 911 * Whichever it is, charge the time as appropriate. 912 * Note that we charge interrupts to the current process, 913 * regardless of whether they are ``for'' that process, 914 * so that we know how much of its real time was spent 915 * in ``non-process'' (i.e., interrupt) work. 916 */ 917 p = curproc; 918 if (CLKF_INTR(frame)) { 919 if (p != NULL) 920 p->p_iticks++; 921 cp_time[CP_INTR]++; 922 } else if (p != NULL) { 923 p->p_sticks++; 924 cp_time[CP_SYS]++; 925 } else 926 cp_time[CP_IDLE]++; 927 } 928 pscnt = psdiv; 929 930 /* 931 * We maintain statistics shown by user-level statistics 932 * programs: the amount of time in each cpu state, and 933 * the amount of time each of DK_NDRIVE ``drives'' is busy. 934 * 935 * XXX should either run linked list of drives, or (better) 936 * grab timestamps in the start & done code. 937 */ 938 for (i = 0; i < DK_NDRIVE; i++) 939 if (dk_busy & (1 << i)) 940 dk_time[i]++; 941 942 /* 943 * We adjust the priority of the current process. The priority of 944 * a process gets worse as it accumulates CPU time. The cpu usage 945 * estimator (p_estcpu) is increased here. The formula for computing 946 * priorities (in kern_synch.c) will compute a different value each 947 * time p_estcpu increases by 4. The cpu usage estimator ramps up 948 * quite quickly when the process is running (linearly), and decays 949 * away exponentially, at a rate which is proportionally slower when 950 * the system is busy. The basic principal is that the system will 951 * 90% forget that the process used a lot of CPU time in 5 * loadav 952 * seconds. This causes the system to favor processes which haven't 953 * run much recently, and to round-robin among other processes. 954 */ 955 if (p != NULL) { 956 p->p_cpticks++; 957 if (++p->p_estcpu == 0) 958 p->p_estcpu--; 959 if ((p->p_estcpu & 3) == 0) { 960 resetpriority(p); 961 if (p->p_priority >= PUSER) 962 p->p_priority = p->p_usrpri; 963 } 964 965 /* Update resource usage integrals and maximums. */ 966 if ((pstats = p->p_stats) != NULL && 967 (ru = &pstats->p_ru) != NULL && 968 (vm = p->p_vmspace) != NULL) { 969 ru->ru_ixrss += vm->vm_tsize * PAGE_SIZE / 1024; 970 ru->ru_idrss += vm->vm_dsize * PAGE_SIZE / 1024; 971 ru->ru_isrss += vm->vm_ssize * PAGE_SIZE / 1024; 972 rss = vm->vm_pmap.pm_stats.resident_count * 973 PAGE_SIZE / 1024; 974 if (ru->ru_maxrss < rss) 975 ru->ru_maxrss = rss; 976 } 977 } 978} 979 980/* 981 * Return information about system clocks. 982 */ 983static int 984sysctl_kern_clockrate SYSCTL_HANDLER_ARGS 985{ 986 struct clockinfo clkinfo; 987 /* 988 * Construct clockinfo structure. 989 */ 990 clkinfo.hz = hz; 991 clkinfo.tick = tick; 992 clkinfo.profhz = profhz; 993 clkinfo.stathz = stathz ? stathz : hz; 994 return (sysctl_handle_opaque(oidp, &clkinfo, sizeof clkinfo, req)); 995} 996 997SYSCTL_PROC(_kern, KERN_CLOCKRATE, clockrate, CTLTYPE_STRUCT|CTLFLAG_RD, 998 0, 0, sysctl_kern_clockrate, "S,clockinfo",""); 999 1000/*#ifdef PPS_SYNC*/ 1001#if 0 1002/* This code is completely bogus; if anybody ever wants to use it, get 1003 * the current version from Dave Mills. */ 1004 1005/* 1006 * hardpps() - discipline CPU clock oscillator to external pps signal 1007 * 1008 * This routine is called at each PPS interrupt in order to discipline 1009 * the CPU clock oscillator to the PPS signal. It integrates successive 1010 * phase differences between the two oscillators and calculates the 1011 * frequency offset. This is used in hardclock() to discipline the CPU 1012 * clock oscillator so that intrinsic frequency error is cancelled out. 1013 * The code requires the caller to capture the time and hardware 1014 * counter value at the designated PPS signal transition. 1015 */ 1016void 1017hardpps(tvp, usec) 1018 struct timeval *tvp; /* time at PPS */ 1019 long usec; /* hardware counter at PPS */ 1020{ 1021 long u_usec, v_usec, bigtick; 1022 long cal_sec, cal_usec; 1023 1024 /* 1025 * During the calibration interval adjust the starting time when 1026 * the tick overflows. At the end of the interval compute the 1027 * duration of the interval and the difference of the hardware 1028 * counters at the beginning and end of the interval. This code 1029 * is deliciously complicated by the fact valid differences may 1030 * exceed the value of tick when using long calibration 1031 * intervals and small ticks. Note that the counter can be 1032 * greater than tick if caught at just the wrong instant, but 1033 * the values returned and used here are correct. 1034 */ 1035 bigtick = (long)tick << SHIFT_USEC; 1036 pps_usec -= ntp_pll.ybar; 1037 if (pps_usec >= bigtick) 1038 pps_usec -= bigtick; 1039 if (pps_usec < 0) 1040 pps_usec += bigtick; 1041 pps_time.tv_sec++; 1042 pps_count++; 1043 if (pps_count < (1 << pps_shift)) 1044 return; 1045 pps_count = 0; 1046 ntp_pll.calcnt++; 1047 u_usec = usec << SHIFT_USEC; 1048 v_usec = pps_usec - u_usec; 1049 if (v_usec >= bigtick >> 1) 1050 v_usec -= bigtick; 1051 if (v_usec < -(bigtick >> 1)) 1052 v_usec += bigtick; 1053 if (v_usec < 0) 1054 v_usec = -(-v_usec >> ntp_pll.shift); 1055 else 1056 v_usec = v_usec >> ntp_pll.shift; 1057 pps_usec = u_usec; 1058 cal_sec = tvp->tv_sec; 1059 cal_usec = tvp->tv_usec; 1060 cal_sec -= pps_time.tv_sec; 1061 cal_usec -= pps_time.tv_usec; 1062 if (cal_usec < 0) { 1063 cal_usec += 1000000; 1064 cal_sec--; 1065 } 1066 pps_time = *tvp; 1067 1068 /* 1069 * Check for lost interrupts, noise, excessive jitter and 1070 * excessive frequency error. The number of timer ticks during 1071 * the interval may vary +-1 tick. Add to this a margin of one 1072 * tick for the PPS signal jitter and maximum frequency 1073 * deviation. If the limits are exceeded, the calibration 1074 * interval is reset to the minimum and we start over. 1075 */ 1076 u_usec = (long)tick << 1; 1077 if (!((cal_sec == -1 && cal_usec > (1000000 - u_usec)) 1078 || (cal_sec == 0 && cal_usec < u_usec)) 1079 || v_usec > ntp_pll.tolerance || v_usec < -ntp_pll.tolerance) { 1080 ntp_pll.jitcnt++; 1081 ntp_pll.shift = NTP_PLL.SHIFT; 1082 pps_dispinc = PPS_DISPINC; 1083 ntp_pll.intcnt = 0; 1084 return; 1085 } 1086 1087 /* 1088 * A three-stage median filter is used to help deglitch the pps 1089 * signal. The median sample becomes the offset estimate; the 1090 * difference between the other two samples becomes the 1091 * dispersion estimate. 1092 */ 1093 pps_mf[2] = pps_mf[1]; 1094 pps_mf[1] = pps_mf[0]; 1095 pps_mf[0] = v_usec; 1096 if (pps_mf[0] > pps_mf[1]) { 1097 if (pps_mf[1] > pps_mf[2]) { 1098 u_usec = pps_mf[1]; /* 0 1 2 */ 1099 v_usec = pps_mf[0] - pps_mf[2]; 1100 } else if (pps_mf[2] > pps_mf[0]) { 1101 u_usec = pps_mf[0]; /* 2 0 1 */ 1102 v_usec = pps_mf[2] - pps_mf[1]; 1103 } else { 1104 u_usec = pps_mf[2]; /* 0 2 1 */ 1105 v_usec = pps_mf[0] - pps_mf[1]; 1106 } 1107 } else { 1108 if (pps_mf[1] < pps_mf[2]) { 1109 u_usec = pps_mf[1]; /* 2 1 0 */ 1110 v_usec = pps_mf[2] - pps_mf[0]; 1111 } else if (pps_mf[2] < pps_mf[0]) { 1112 u_usec = pps_mf[0]; /* 1 0 2 */ 1113 v_usec = pps_mf[1] - pps_mf[2]; 1114 } else { 1115 u_usec = pps_mf[2]; /* 1 2 0 */ 1116 v_usec = pps_mf[1] - pps_mf[0]; 1117 } 1118 } 1119 1120 /* 1121 * Here the dispersion average is updated. If it is less than 1122 * the threshold pps_dispmax, the frequency average is updated 1123 * as well, but clamped to the tolerance. 1124 */ 1125 v_usec = (v_usec >> 1) - ntp_pll.disp; 1126 if (v_usec < 0) 1127 ntp_pll.disp -= -v_usec >> PPS_AVG; 1128 else 1129 ntp_pll.disp += v_usec >> PPS_AVG; 1130 if (ntp_pll.disp > pps_dispmax) { 1131 ntp_pll.discnt++; 1132 return; 1133 } 1134 if (u_usec < 0) { 1135 ntp_pll.ybar -= -u_usec >> PPS_AVG; 1136 if (ntp_pll.ybar < -ntp_pll.tolerance) 1137 ntp_pll.ybar = -ntp_pll.tolerance; 1138 u_usec = -u_usec; 1139 } else { 1140 ntp_pll.ybar += u_usec >> PPS_AVG; 1141 if (ntp_pll.ybar > ntp_pll.tolerance) 1142 ntp_pll.ybar = ntp_pll.tolerance; 1143 } 1144 1145 /* 1146 * Here the calibration interval is adjusted. If the maximum 1147 * time difference is greater than tick/4, reduce the interval 1148 * by half. If this is not the case for four consecutive 1149 * intervals, double the interval. 1150 */ 1151 if (u_usec << ntp_pll.shift > bigtick >> 2) { 1152 ntp_pll.intcnt = 0; 1153 if (ntp_pll.shift > NTP_PLL.SHIFT) { 1154 ntp_pll.shift--; 1155 pps_dispinc <<= 1; 1156 } 1157 } else if (ntp_pll.intcnt >= 4) { 1158 ntp_pll.intcnt = 0; 1159 if (ntp_pll.shift < NTP_PLL.SHIFTMAX) { 1160 ntp_pll.shift++; 1161 pps_dispinc >>= 1; 1162 } 1163 } else 1164 ntp_pll.intcnt++; 1165} 1166#endif /* PPS_SYNC */ 1167