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