kern_clock.c revision 33134
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.54 1998/02/04 22:32:30 eivind Exp $ 40 */ 41 42#include <sys/param.h> 43#include <sys/systm.h> 44#include <sys/dkstat.h> 45#include <sys/callout.h> 46#include <sys/kernel.h> 47#include <sys/proc.h> 48#include <sys/resourcevar.h> 49#include <sys/signalvar.h> 50#include <sys/timex.h> 51#include <vm/vm.h> 52#include <sys/lock.h> 53#include <vm/pmap.h> 54#include <vm/vm_map.h> 55#include <sys/sysctl.h> 56 57#include <machine/cpu.h> 58#define CLOCK_HAIR /* XXX */ 59#include <machine/clock.h> 60#include <machine/limits.h> 61 62#ifdef GPROF 63#include <sys/gmon.h> 64#endif 65 66#if defined(SMP) && defined(BETTER_CLOCK) 67#include <machine/smp.h> 68#endif 69 70static void initclocks __P((void *dummy)); 71SYSINIT(clocks, SI_SUB_CLOCKS, SI_ORDER_FIRST, initclocks, NULL) 72 73/* Some of these don't belong here, but it's easiest to concentrate them. */ 74#if defined(SMP) && defined(BETTER_CLOCK) 75long cp_time[CPUSTATES]; 76#else 77static long cp_time[CPUSTATES]; 78#endif 79long dk_seek[DK_NDRIVE]; 80static long dk_time[DK_NDRIVE]; /* time busy (in statclock ticks) */ 81long dk_wds[DK_NDRIVE]; 82long dk_wpms[DK_NDRIVE]; 83long dk_xfer[DK_NDRIVE]; 84 85int dk_busy; 86int dk_ndrive = 0; 87char dk_names[DK_NDRIVE][DK_NAMELEN]; 88 89long tk_cancc; 90long tk_nin; 91long tk_nout; 92long tk_rawcc; 93 94/* 95 * Clock handling routines. 96 * 97 * This code is written to operate with two timers that run independently of 98 * each other. The main clock, running hz times per second, is used to keep 99 * track of real time. The second timer handles kernel and user profiling, 100 * and does resource use estimation. If the second timer is programmable, 101 * it is randomized to avoid aliasing between the two clocks. For example, 102 * the randomization prevents an adversary from always giving up the cpu 103 * just before its quantum expires. Otherwise, it would never accumulate 104 * cpu ticks. The mean frequency of the second timer is stathz. 105 * 106 * If no second timer exists, stathz will be zero; in this case we drive 107 * profiling and statistics off the main clock. This WILL NOT be accurate; 108 * do not do it unless absolutely necessary. 109 * 110 * The statistics clock may (or may not) be run at a higher rate while 111 * profiling. This profile clock runs at profhz. We require that profhz 112 * be an integral multiple of stathz. 113 * 114 * If the statistics clock is running fast, it must be divided by the ratio 115 * profhz/stathz for statistics. (For profiling, every tick counts.) 116 */ 117 118/* 119 * TODO: 120 * allocate more timeout table slots when table overflows. 121 */ 122 123/* 124 * Bump a timeval by a small number of usec's. 125 */ 126#define BUMPTIME(t, usec) { \ 127 register volatile struct timeval *tp = (t); \ 128 register long us; \ 129 \ 130 tp->tv_usec = us = tp->tv_usec + (usec); \ 131 if (us >= 1000000) { \ 132 tp->tv_usec = us - 1000000; \ 133 tp->tv_sec++; \ 134 } \ 135} 136 137int stathz; 138int profhz; 139static int profprocs; 140int ticks; 141static int psdiv, pscnt; /* prof => stat divider */ 142int psratio; /* ratio: prof / stat */ 143 144volatile struct timeval time; 145volatile struct timeval mono_time; 146 147/* 148 * Initialize clock frequencies and start both clocks running. 149 */ 150/* ARGSUSED*/ 151static void 152initclocks(dummy) 153 void *dummy; 154{ 155 register int i; 156 157 /* 158 * Set divisors to 1 (normal case) and let the machine-specific 159 * code do its bit. 160 */ 161 psdiv = pscnt = 1; 162 cpu_initclocks(); 163 164 /* 165 * Compute profhz/stathz, and fix profhz if needed. 166 */ 167 i = stathz ? stathz : hz; 168 if (profhz == 0) 169 profhz = i; 170 psratio = profhz / i; 171} 172 173/* 174 * The real-time timer, interrupting hz times per second. 175 */ 176void 177hardclock(frame) 178 register struct clockframe *frame; 179{ 180 register struct proc *p; 181 int time_update; 182 struct timeval newtime = time; 183 long ltemp; 184 185 p = curproc; 186 if (p) { 187 register struct pstats *pstats; 188 189 /* 190 * Run current process's virtual and profile time, as needed. 191 */ 192 pstats = p->p_stats; 193 if (CLKF_USERMODE(frame) && 194 timerisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) && 195 itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0) 196 psignal(p, SIGVTALRM); 197 if (timerisset(&pstats->p_timer[ITIMER_PROF].it_value) && 198 itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0) 199 psignal(p, SIGPROF); 200 } 201 202#if defined(SMP) && defined(BETTER_CLOCK) 203 forward_hardclock(pscnt); 204#endif 205 /* 206 * If no separate statistics clock is available, run it from here. 207 */ 208 if (stathz == 0) 209 statclock(frame); 210 211 /* 212 * Increment the time-of-day. 213 */ 214 ticks++; 215 216 if (timedelta == 0) { 217 time_update = CPU_THISTICKLEN(tick); 218 } else { 219 time_update = CPU_THISTICKLEN(tick) + tickdelta; 220 timedelta -= tickdelta; 221 } 222 BUMPTIME(&mono_time, time_update); 223 224 /* 225 * Compute the phase adjustment. If the low-order bits 226 * (time_phase) of the update overflow, bump the high-order bits 227 * (time_update). 228 */ 229 time_phase += time_adj; 230 if (time_phase <= -FINEUSEC) { 231 ltemp = -time_phase >> SHIFT_SCALE; 232 time_phase += ltemp << SHIFT_SCALE; 233 time_update -= ltemp; 234 } 235 else if (time_phase >= FINEUSEC) { 236 ltemp = time_phase >> SHIFT_SCALE; 237 time_phase -= ltemp << SHIFT_SCALE; 238 time_update += ltemp; 239 } 240 241 newtime.tv_usec += time_update; 242 /* 243 * On rollover of the second the phase adjustment to be used for 244 * the next second is calculated. Also, the maximum error is 245 * increased by the tolerance. If the PPS frequency discipline 246 * code is present, the phase is increased to compensate for the 247 * CPU clock oscillator frequency error. 248 * 249 * On a 32-bit machine and given parameters in the timex.h 250 * header file, the maximum phase adjustment is +-512 ms and 251 * maximum frequency offset is a tad less than) +-512 ppm. On a 252 * 64-bit machine, you shouldn't need to ask. 253 */ 254 if (newtime.tv_usec >= 1000000) { 255 newtime.tv_usec -= 1000000; 256 newtime.tv_sec++; 257 ntp_update_second(&newtime.tv_sec); 258 } 259 CPU_CLOCKUPDATE(&time, &newtime); 260 261 if (TAILQ_FIRST(&callwheel[ticks & callwheelmask]) != NULL) 262 setsoftclock(); 263} 264 265void 266gettime(struct timeval *tvp) 267{ 268 int s; 269 270 s = splclock(); 271 /* XXX should use microtime() iff tv_usec is used. */ 272 *tvp = time; 273 splx(s); 274} 275 276/* 277 * Compute number of hz until specified time. Used to 278 * compute third argument to timeout() from an absolute time. 279 */ 280int 281hzto(tv) 282 struct timeval *tv; 283{ 284 register unsigned long ticks; 285 register long sec, usec; 286 int s; 287 288 /* 289 * If the number of usecs in the whole seconds part of the time 290 * difference fits in a long, then the total number of usecs will 291 * fit in an unsigned long. Compute the total and convert it to 292 * ticks, rounding up and adding 1 to allow for the current tick 293 * to expire. Rounding also depends on unsigned long arithmetic 294 * to avoid overflow. 295 * 296 * Otherwise, if the number of ticks in the whole seconds part of 297 * the time difference fits in a long, then convert the parts to 298 * ticks separately and add, using similar rounding methods and 299 * overflow avoidance. This method would work in the previous 300 * case but it is slightly slower and assumes that hz is integral. 301 * 302 * Otherwise, round the time difference down to the maximum 303 * representable value. 304 * 305 * If ints have 32 bits, then the maximum value for any timeout in 306 * 10ms ticks is 248 days. 307 */ 308 s = splclock(); 309 sec = tv->tv_sec - time.tv_sec; 310 usec = tv->tv_usec - time.tv_usec; 311 splx(s); 312 if (usec < 0) { 313 sec--; 314 usec += 1000000; 315 } 316 if (sec < 0) { 317#ifdef DIAGNOSTIC 318 printf("hzto: negative time difference %ld sec %ld usec\n", 319 sec, usec); 320#endif 321 ticks = 1; 322 } else if (sec <= LONG_MAX / 1000000) 323 ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1)) 324 / tick + 1; 325 else if (sec <= LONG_MAX / hz) 326 ticks = sec * hz 327 + ((unsigned long)usec + (tick - 1)) / tick + 1; 328 else 329 ticks = LONG_MAX; 330 if (ticks > INT_MAX) 331 ticks = INT_MAX; 332 return (ticks); 333} 334 335/* 336 * Start profiling on a process. 337 * 338 * Kernel profiling passes proc0 which never exits and hence 339 * keeps the profile clock running constantly. 340 */ 341void 342startprofclock(p) 343 register struct proc *p; 344{ 345 int s; 346 347 if ((p->p_flag & P_PROFIL) == 0) { 348 p->p_flag |= P_PROFIL; 349 if (++profprocs == 1 && stathz != 0) { 350 s = splstatclock(); 351 psdiv = pscnt = psratio; 352 setstatclockrate(profhz); 353 splx(s); 354 } 355 } 356} 357 358/* 359 * Stop profiling on a process. 360 */ 361void 362stopprofclock(p) 363 register struct proc *p; 364{ 365 int s; 366 367 if (p->p_flag & P_PROFIL) { 368 p->p_flag &= ~P_PROFIL; 369 if (--profprocs == 0 && stathz != 0) { 370 s = splstatclock(); 371 psdiv = pscnt = 1; 372 setstatclockrate(stathz); 373 splx(s); 374 } 375 } 376} 377 378/* 379 * Statistics clock. Grab profile sample, and if divider reaches 0, 380 * do process and kernel statistics. 381 */ 382void 383statclock(frame) 384 register struct clockframe *frame; 385{ 386#ifdef GPROF 387 register struct gmonparam *g; 388#endif 389 register struct proc *p; 390 register int i; 391 struct pstats *pstats; 392 long rss; 393 struct rusage *ru; 394 struct vmspace *vm; 395 396 if (CLKF_USERMODE(frame)) { 397 p = curproc; 398 if (p->p_flag & P_PROFIL) 399 addupc_intr(p, CLKF_PC(frame), 1); 400#if defined(SMP) && defined(BETTER_CLOCK) 401 if (stathz != 0) 402 forward_statclock(pscnt); 403#endif 404 if (--pscnt > 0) 405 return; 406 /* 407 * Came from user mode; CPU was in user state. 408 * If this process is being profiled record the tick. 409 */ 410 p->p_uticks++; 411 if (p->p_nice > NZERO) 412 cp_time[CP_NICE]++; 413 else 414 cp_time[CP_USER]++; 415 } else { 416#ifdef GPROF 417 /* 418 * Kernel statistics are just like addupc_intr, only easier. 419 */ 420 g = &_gmonparam; 421 if (g->state == GMON_PROF_ON) { 422 i = CLKF_PC(frame) - g->lowpc; 423 if (i < g->textsize) { 424 i /= HISTFRACTION * sizeof(*g->kcount); 425 g->kcount[i]++; 426 } 427 } 428#endif 429#if defined(SMP) && defined(BETTER_CLOCK) 430 if (stathz != 0) 431 forward_statclock(pscnt); 432#endif 433 if (--pscnt > 0) 434 return; 435 /* 436 * Came from kernel mode, so we were: 437 * - handling an interrupt, 438 * - doing syscall or trap work on behalf of the current 439 * user process, or 440 * - spinning in the idle loop. 441 * Whichever it is, charge the time as appropriate. 442 * Note that we charge interrupts to the current process, 443 * regardless of whether they are ``for'' that process, 444 * so that we know how much of its real time was spent 445 * in ``non-process'' (i.e., interrupt) work. 446 */ 447 p = curproc; 448 if (CLKF_INTR(frame)) { 449 if (p != NULL) 450 p->p_iticks++; 451 cp_time[CP_INTR]++; 452 } else if (p != NULL) { 453 p->p_sticks++; 454 cp_time[CP_SYS]++; 455 } else 456 cp_time[CP_IDLE]++; 457 } 458 pscnt = psdiv; 459 460 /* 461 * We maintain statistics shown by user-level statistics 462 * programs: the amount of time in each cpu state, and 463 * the amount of time each of DK_NDRIVE ``drives'' is busy. 464 * 465 * XXX should either run linked list of drives, or (better) 466 * grab timestamps in the start & done code. 467 */ 468 for (i = 0; i < DK_NDRIVE; i++) 469 if (dk_busy & (1 << i)) 470 dk_time[i]++; 471 472 /* 473 * We adjust the priority of the current process. The priority of 474 * a process gets worse as it accumulates CPU time. The cpu usage 475 * estimator (p_estcpu) is increased here. The formula for computing 476 * priorities (in kern_synch.c) will compute a different value each 477 * time p_estcpu increases by 4. The cpu usage estimator ramps up 478 * quite quickly when the process is running (linearly), and decays 479 * away exponentially, at a rate which is proportionally slower when 480 * the system is busy. The basic principal is that the system will 481 * 90% forget that the process used a lot of CPU time in 5 * loadav 482 * seconds. This causes the system to favor processes which haven't 483 * run much recently, and to round-robin among other processes. 484 */ 485 if (p != NULL) { 486 p->p_cpticks++; 487 if (++p->p_estcpu == 0) 488 p->p_estcpu--; 489 if ((p->p_estcpu & 3) == 0) { 490 resetpriority(p); 491 if (p->p_priority >= PUSER) 492 p->p_priority = p->p_usrpri; 493 } 494 495 /* Update resource usage integrals and maximums. */ 496 if ((pstats = p->p_stats) != NULL && 497 (ru = &pstats->p_ru) != NULL && 498 (vm = p->p_vmspace) != NULL) { 499 ru->ru_ixrss += vm->vm_tsize * PAGE_SIZE / 1024; 500 ru->ru_idrss += vm->vm_dsize * PAGE_SIZE / 1024; 501 ru->ru_isrss += vm->vm_ssize * PAGE_SIZE / 1024; 502 rss = vm->vm_pmap.pm_stats.resident_count * 503 PAGE_SIZE / 1024; 504 if (ru->ru_maxrss < rss) 505 ru->ru_maxrss = rss; 506 } 507 } 508} 509 510/* 511 * Return information about system clocks. 512 */ 513static int 514sysctl_kern_clockrate SYSCTL_HANDLER_ARGS 515{ 516 struct clockinfo clkinfo; 517 /* 518 * Construct clockinfo structure. 519 */ 520 clkinfo.hz = hz; 521 clkinfo.tick = tick; 522 clkinfo.tickadj = tickadj; 523 clkinfo.profhz = profhz; 524 clkinfo.stathz = stathz ? stathz : hz; 525 return (sysctl_handle_opaque(oidp, &clkinfo, sizeof clkinfo, req)); 526} 527 528SYSCTL_PROC(_kern, KERN_CLOCKRATE, clockrate, CTLTYPE_STRUCT|CTLFLAG_RD, 529 0, 0, sysctl_kern_clockrate, "S,clockinfo",""); 530 531