1 /* $OpenBSD: kern_clock.c,v 1.84 2013/12/24 01:11:00 tedu Exp $ */ 2 /* $NetBSD: kern_clock.c,v 1.34 1996/06/09 04:51:03 briggs Exp $ */ 3 4 /*- 5 * Copyright (c) 1982, 1986, 1991, 1993 6 * The Regents of the University of California. All rights reserved. 7 * (c) UNIX System Laboratories, Inc. 8 * All or some portions of this file are derived from material licensed 9 * to the University of California by American Telephone and Telegraph 10 * Co. or Unix System Laboratories, Inc. and are reproduced herein with 11 * the permission of UNIX System Laboratories, Inc. 12 * 13 * Redistribution and use in source and binary forms, with or without 14 * modification, are permitted provided that the following conditions 15 * are met: 16 * 1. Redistributions of source code must retain the above copyright 17 * notice, this list of conditions and the following disclaimer. 18 * 2. Redistributions in binary form must reproduce the above copyright 19 * notice, this list of conditions and the following disclaimer in the 20 * documentation and/or other materials provided with the distribution. 21 * 3. Neither the name of the University nor the names of its contributors 22 * may be used to endorse or promote products derived from this software 23 * without specific prior written permission. 24 * 25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 35 * SUCH DAMAGE. 36 * 37 * @(#)kern_clock.c 8.5 (Berkeley) 1/21/94 38 */ 39 40 #include <sys/param.h> 41 #include <sys/systm.h> 42 #include <sys/dkstat.h> 43 #include <sys/timeout.h> 44 #include <sys/kernel.h> 45 #include <sys/limits.h> 46 #include <sys/proc.h> 47 #include <sys/user.h> 48 #include <sys/resourcevar.h> 49 #include <sys/signalvar.h> 50 #include <uvm/uvm_extern.h> 51 #include <sys/sysctl.h> 52 #include <sys/sched.h> 53 #include <sys/timetc.h> 54 55 56 #ifdef GPROF 57 #include <sys/gmon.h> 58 #endif 59 60 /* 61 * Clock handling routines. 62 * 63 * This code is written to operate with two timers that run independently of 64 * each other. The main clock, running hz times per second, is used to keep 65 * track of real time. The second timer handles kernel and user profiling, 66 * and does resource use estimation. If the second timer is programmable, 67 * it is randomized to avoid aliasing between the two clocks. For example, 68 * the randomization prevents an adversary from always giving up the cpu 69 * just before its quantum expires. Otherwise, it would never accumulate 70 * cpu ticks. The mean frequency of the second timer is stathz. 71 * 72 * If no second timer exists, stathz will be zero; in this case we drive 73 * profiling and statistics off the main clock. This WILL NOT be accurate; 74 * do not do it unless absolutely necessary. 75 * 76 * The statistics clock may (or may not) be run at a higher rate while 77 * profiling. This profile clock runs at profhz. We require that profhz 78 * be an integral multiple of stathz. 79 * 80 * If the statistics clock is running fast, it must be divided by the ratio 81 * profhz/stathz for statistics. (For profiling, every tick counts.) 82 */ 83 84 /* 85 * Bump a timeval by a small number of usec's. 86 */ 87 #define BUMPTIME(t, usec) { \ 88 volatile struct timeval *tp = (t); \ 89 long us; \ 90 \ 91 tp->tv_usec = us = tp->tv_usec + (usec); \ 92 if (us >= 1000000) { \ 93 tp->tv_usec = us - 1000000; \ 94 tp->tv_sec++; \ 95 } \ 96 } 97 98 int stathz; 99 int schedhz; 100 int profhz; 101 int profprocs; 102 int ticks; 103 static int psdiv, pscnt; /* prof => stat divider */ 104 int psratio; /* ratio: prof / stat */ 105 106 long cp_time[CPUSTATES]; 107 108 void *softclock_si; 109 110 /* 111 * Initialize clock frequencies and start both clocks running. 112 */ 113 void 114 initclocks(void) 115 { 116 int i; 117 118 softclock_si = softintr_establish(IPL_SOFTCLOCK, softclock, NULL); 119 if (softclock_si == NULL) 120 panic("initclocks: unable to register softclock intr"); 121 122 /* 123 * Set divisors to 1 (normal case) and let the machine-specific 124 * code do its bit. 125 */ 126 psdiv = pscnt = 1; 127 cpu_initclocks(); 128 129 /* 130 * Compute profhz/stathz, and fix profhz if needed. 131 */ 132 i = stathz ? stathz : hz; 133 if (profhz == 0) 134 profhz = i; 135 psratio = profhz / i; 136 137 /* For very large HZ, ensure that division by 0 does not occur later */ 138 if (tickadj == 0) 139 tickadj = 1; 140 141 inittimecounter(); 142 } 143 144 /* 145 * hardclock does the accounting needed for ITIMER_PROF and ITIMER_VIRTUAL. 146 * We don't want to send signals with psignal from hardclock because it makes 147 * MULTIPROCESSOR locking very complicated. Instead, to use an idea from 148 * FreeBSD, we set a flag on the thread and when it goes to return to 149 * userspace it signals itself. 150 */ 151 152 /* 153 * The real-time timer, interrupting hz times per second. 154 */ 155 void 156 hardclock(struct clockframe *frame) 157 { 158 struct proc *p; 159 struct cpu_info *ci = curcpu(); 160 161 p = curproc; 162 if (p && ((p->p_flag & (P_SYSTEM | P_WEXIT)) == 0)) { 163 struct process *pr = p->p_p; 164 165 /* 166 * Run current process's virtual and profile time, as needed. 167 */ 168 if (CLKF_USERMODE(frame) && 169 timerisset(&pr->ps_timer[ITIMER_VIRTUAL].it_value) && 170 itimerdecr(&pr->ps_timer[ITIMER_VIRTUAL], tick) == 0) { 171 atomic_setbits_int(&p->p_flag, P_ALRMPEND); 172 need_proftick(p); 173 } 174 if (timerisset(&pr->ps_timer[ITIMER_PROF].it_value) && 175 itimerdecr(&pr->ps_timer[ITIMER_PROF], tick) == 0) { 176 atomic_setbits_int(&p->p_flag, P_PROFPEND); 177 need_proftick(p); 178 } 179 } 180 181 /* 182 * If no separate statistics clock is available, run it from here. 183 */ 184 if (stathz == 0) 185 statclock(frame); 186 187 if (--ci->ci_schedstate.spc_rrticks <= 0) 188 roundrobin(ci); 189 190 /* 191 * If we are not the primary CPU, we're not allowed to do 192 * any more work. 193 */ 194 if (CPU_IS_PRIMARY(ci) == 0) 195 return; 196 197 tc_ticktock(); 198 199 /* 200 * Update real-time timeout queue. 201 * Process callouts at a very low cpu priority, so we don't keep the 202 * relatively high clock interrupt priority any longer than necessary. 203 */ 204 if (timeout_hardclock_update()) 205 softintr_schedule(softclock_si); 206 } 207 208 /* 209 * Compute number of hz until specified time. Used to 210 * compute the second argument to timeout_add() from an absolute time. 211 */ 212 int 213 hzto(const struct timeval *tv) 214 { 215 struct timeval now; 216 unsigned long nticks; 217 long sec, usec; 218 219 /* 220 * If the number of usecs in the whole seconds part of the time 221 * difference fits in a long, then the total number of usecs will 222 * fit in an unsigned long. Compute the total and convert it to 223 * ticks, rounding up and adding 1 to allow for the current tick 224 * to expire. Rounding also depends on unsigned long arithmetic 225 * to avoid overflow. 226 * 227 * Otherwise, if the number of ticks in the whole seconds part of 228 * the time difference fits in a long, then convert the parts to 229 * ticks separately and add, using similar rounding methods and 230 * overflow avoidance. This method would work in the previous 231 * case but it is slightly slower and assumes that hz is integral. 232 * 233 * Otherwise, round the time difference down to the maximum 234 * representable value. 235 * 236 * If ints have 32 bits, then the maximum value for any timeout in 237 * 10ms ticks is 248 days. 238 */ 239 getmicrotime(&now); 240 sec = tv->tv_sec - now.tv_sec; 241 usec = tv->tv_usec - now.tv_usec; 242 if (usec < 0) { 243 sec--; 244 usec += 1000000; 245 } 246 if (sec < 0 || (sec == 0 && usec <= 0)) { 247 nticks = 0; 248 } else if (sec <= LONG_MAX / 1000000) 249 nticks = (sec * 1000000 + (unsigned long)usec + (tick - 1)) 250 / tick + 1; 251 else if (sec <= LONG_MAX / hz) 252 nticks = sec * hz 253 + ((unsigned long)usec + (tick - 1)) / tick + 1; 254 else 255 nticks = LONG_MAX; 256 if (nticks > INT_MAX) 257 nticks = INT_MAX; 258 return ((int)nticks); 259 } 260 261 /* 262 * Compute number of hz in the specified amount of time. 263 */ 264 int 265 tvtohz(const struct timeval *tv) 266 { 267 unsigned long nticks; 268 time_t sec; 269 long usec; 270 271 /* 272 * If the number of usecs in the whole seconds part of the time 273 * fits in a long, then the total number of usecs will 274 * fit in an unsigned long. Compute the total and convert it to 275 * ticks, rounding up and adding 1 to allow for the current tick 276 * to expire. Rounding also depends on unsigned long arithmetic 277 * to avoid overflow. 278 * 279 * Otherwise, if the number of ticks in the whole seconds part of 280 * the time fits in a long, then convert the parts to 281 * ticks separately and add, using similar rounding methods and 282 * overflow avoidance. This method would work in the previous 283 * case but it is slightly slower and assumes that hz is integral. 284 * 285 * Otherwise, round the time down to the maximum 286 * representable value. 287 * 288 * If ints have 32 bits, then the maximum value for any timeout in 289 * 10ms ticks is 248 days. 290 */ 291 sec = tv->tv_sec; 292 usec = tv->tv_usec; 293 if (sec < 0 || (sec == 0 && usec <= 0)) 294 nticks = 0; 295 else if (sec <= LONG_MAX / 1000000) 296 nticks = (sec * 1000000 + (unsigned long)usec + (tick - 1)) 297 / tick + 1; 298 else if (sec <= LONG_MAX / hz) 299 nticks = sec * hz 300 + ((unsigned long)usec + (tick - 1)) / tick + 1; 301 else 302 nticks = LONG_MAX; 303 if (nticks > INT_MAX) 304 nticks = INT_MAX; 305 return ((int)nticks); 306 } 307 308 int 309 tstohz(const struct timespec *ts) 310 { 311 struct timeval tv; 312 TIMESPEC_TO_TIMEVAL(&tv, ts); 313 314 /* Round up. */ 315 if ((ts->tv_nsec % 1000) != 0) { 316 tv.tv_usec += 1; 317 if (tv.tv_usec >= 1000000) { 318 tv.tv_usec -= 1000000; 319 tv.tv_sec += 1; 320 } 321 } 322 323 return (tvtohz(&tv)); 324 } 325 326 /* 327 * Start profiling on a process. 328 * 329 * Kernel profiling passes proc0 which never exits and hence 330 * keeps the profile clock running constantly. 331 */ 332 void 333 startprofclock(struct process *pr) 334 { 335 int s; 336 337 if ((pr->ps_flags & PS_PROFIL) == 0) { 338 atomic_setbits_int(&pr->ps_flags, PS_PROFIL); 339 if (++profprocs == 1 && stathz != 0) { 340 s = splstatclock(); 341 psdiv = pscnt = psratio; 342 setstatclockrate(profhz); 343 splx(s); 344 } 345 } 346 } 347 348 /* 349 * Stop profiling on a process. 350 */ 351 void 352 stopprofclock(struct process *pr) 353 { 354 int s; 355 356 if (pr->ps_flags & PS_PROFIL) { 357 atomic_clearbits_int(&pr->ps_flags, PS_PROFIL); 358 if (--profprocs == 0 && stathz != 0) { 359 s = splstatclock(); 360 psdiv = pscnt = 1; 361 setstatclockrate(stathz); 362 splx(s); 363 } 364 } 365 } 366 367 /* 368 * Statistics clock. Grab profile sample, and if divider reaches 0, 369 * do process and kernel statistics. 370 */ 371 void 372 statclock(struct clockframe *frame) 373 { 374 #ifdef GPROF 375 struct gmonparam *g; 376 u_long i; 377 #endif 378 struct cpu_info *ci = curcpu(); 379 struct schedstate_percpu *spc = &ci->ci_schedstate; 380 struct proc *p = curproc; 381 struct process *pr; 382 383 /* 384 * Notice changes in divisor frequency, and adjust clock 385 * frequency accordingly. 386 */ 387 if (spc->spc_psdiv != psdiv) { 388 spc->spc_psdiv = psdiv; 389 spc->spc_pscnt = psdiv; 390 if (psdiv == 1) { 391 setstatclockrate(stathz); 392 } else { 393 setstatclockrate(profhz); 394 } 395 } 396 397 if (CLKF_USERMODE(frame)) { 398 pr = p->p_p; 399 if (pr->ps_flags & PS_PROFIL) 400 addupc_intr(p, CLKF_PC(frame)); 401 if (--spc->spc_pscnt > 0) 402 return; 403 /* 404 * Came from user mode; CPU was in user state. 405 * If this process is being profiled record the tick. 406 */ 407 p->p_uticks++; 408 if (pr->ps_nice > NZERO) 409 spc->spc_cp_time[CP_NICE]++; 410 else 411 spc->spc_cp_time[CP_USER]++; 412 } else { 413 #ifdef GPROF 414 /* 415 * Kernel statistics are just like addupc_intr, only easier. 416 */ 417 g = ci->ci_gmon; 418 if (g != NULL && g->state == GMON_PROF_ON) { 419 i = CLKF_PC(frame) - g->lowpc; 420 if (i < g->textsize) { 421 i /= HISTFRACTION * sizeof(*g->kcount); 422 g->kcount[i]++; 423 } 424 } 425 #endif 426 #if defined(PROC_PC) 427 if (p != NULL && p->p_p->ps_flags & PS_PROFIL) 428 addupc_intr(p, PROC_PC(p)); 429 #endif 430 if (--spc->spc_pscnt > 0) 431 return; 432 /* 433 * Came from kernel mode, so we were: 434 * - handling an interrupt, 435 * - doing syscall or trap work on behalf of the current 436 * user process, or 437 * - spinning in the idle loop. 438 * Whichever it is, charge the time as appropriate. 439 * Note that we charge interrupts to the current process, 440 * regardless of whether they are ``for'' that process, 441 * so that we know how much of its real time was spent 442 * in ``non-process'' (i.e., interrupt) work. 443 */ 444 if (CLKF_INTR(frame)) { 445 if (p != NULL) 446 p->p_iticks++; 447 spc->spc_cp_time[CP_INTR]++; 448 } else if (p != NULL && p != spc->spc_idleproc) { 449 p->p_sticks++; 450 spc->spc_cp_time[CP_SYS]++; 451 } else 452 spc->spc_cp_time[CP_IDLE]++; 453 } 454 spc->spc_pscnt = psdiv; 455 456 if (p != NULL) { 457 p->p_cpticks++; 458 /* 459 * If no schedclock is provided, call it here at ~~12-25 Hz; 460 * ~~16 Hz is best 461 */ 462 if (schedhz == 0) { 463 if ((++curcpu()->ci_schedstate.spc_schedticks & 3) == 464 0) 465 schedclock(p); 466 } 467 } 468 } 469 470 /* 471 * Return information about system clocks. 472 */ 473 int 474 sysctl_clockrate(char *where, size_t *sizep, void *newp) 475 { 476 struct clockinfo clkinfo; 477 478 /* 479 * Construct clockinfo structure. 480 */ 481 clkinfo.tick = tick; 482 clkinfo.tickadj = tickadj; 483 clkinfo.hz = hz; 484 clkinfo.profhz = profhz; 485 clkinfo.stathz = stathz ? stathz : hz; 486 return (sysctl_rdstruct(where, sizep, newp, &clkinfo, sizeof(clkinfo))); 487 } 488