1 /* $OpenBSD: kern_clock.c,v 1.106 2023/02/04 19:33:03 cheloha 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/timeout.h> 43 #include <sys/kernel.h> 44 #include <sys/limits.h> 45 #include <sys/proc.h> 46 #include <sys/user.h> 47 #include <sys/resourcevar.h> 48 #include <sys/sysctl.h> 49 #include <sys/sched.h> 50 #include <sys/timetc.h> 51 52 #if defined(GPROF) || defined(DDBPROF) 53 #include <sys/gmon.h> 54 #endif 55 56 #include "dt.h" 57 #if NDT > 0 58 #include <dev/dt/dtvar.h> 59 #endif 60 61 /* 62 * Clock handling routines. 63 * 64 * This code is written to operate with two timers that run independently of 65 * each other. The main clock, running hz times per second, is used to keep 66 * track of real time. The second timer handles kernel and user profiling, 67 * and does resource use estimation. If the second timer is programmable, 68 * it is randomized to avoid aliasing between the two clocks. For example, 69 * the randomization prevents an adversary from always giving up the cpu 70 * just before its quantum expires. Otherwise, it would never accumulate 71 * cpu ticks. The mean frequency of the second timer is stathz. 72 * 73 * If no second timer exists, stathz will be zero; in this case we drive 74 * profiling and statistics off the main clock. This WILL NOT be accurate; 75 * do not do it unless absolutely necessary. 76 * 77 * The statistics clock may (or may not) be run at a higher rate while 78 * profiling. This profile clock runs at profhz. We require that profhz 79 * be an integral multiple of stathz. 80 * 81 * If the statistics clock is running fast, it must be divided by the ratio 82 * profhz/stathz for statistics. (For profiling, every tick counts.) 83 */ 84 85 int stathz; 86 int schedhz; 87 int profhz; 88 int profprocs; 89 int ticks; 90 static int psdiv, pscnt; /* prof => stat divider */ 91 int psratio; /* ratio: prof / stat */ 92 93 volatile unsigned long jiffies; /* XXX Linux API for drm(4) */ 94 95 /* 96 * Initialize clock frequencies and start both clocks running. 97 */ 98 void 99 initclocks(void) 100 { 101 ticks = INT_MAX - (15 * 60 * hz); 102 jiffies = ULONG_MAX - (10 * 60 * hz); 103 104 /* 105 * Set divisors to 1 (normal case) and let the machine-specific 106 * code do its bit. 107 */ 108 psdiv = pscnt = 1; 109 cpu_initclocks(); 110 111 /* 112 * Compute profhz/stathz. 113 */ 114 psratio = profhz / stathz; 115 116 inittimecounter(); 117 } 118 119 /* 120 * hardclock does the accounting needed for ITIMER_PROF and ITIMER_VIRTUAL. 121 * We don't want to send signals with psignal from hardclock because it makes 122 * MULTIPROCESSOR locking very complicated. Instead, to use an idea from 123 * FreeBSD, we set a flag on the thread and when it goes to return to 124 * userspace it signals itself. 125 */ 126 127 /* 128 * The real-time timer, interrupting hz times per second. 129 */ 130 void 131 hardclock(struct clockframe *frame) 132 { 133 struct proc *p; 134 struct cpu_info *ci = curcpu(); 135 136 p = curproc; 137 if (p && ((p->p_flag & (P_SYSTEM | P_WEXIT)) == 0)) { 138 struct process *pr = p->p_p; 139 140 /* 141 * Run current process's virtual and profile time, as needed. 142 */ 143 if (CLKF_USERMODE(frame) && 144 timespecisset(&pr->ps_timer[ITIMER_VIRTUAL].it_value) && 145 itimerdecr(&pr->ps_timer[ITIMER_VIRTUAL], tick_nsec) == 0) { 146 atomic_setbits_int(&p->p_flag, P_ALRMPEND); 147 need_proftick(p); 148 } 149 if (timespecisset(&pr->ps_timer[ITIMER_PROF].it_value) && 150 itimerdecr(&pr->ps_timer[ITIMER_PROF], tick_nsec) == 0) { 151 atomic_setbits_int(&p->p_flag, P_PROFPEND); 152 need_proftick(p); 153 } 154 } 155 156 if (--ci->ci_schedstate.spc_rrticks <= 0) 157 roundrobin(ci); 158 159 #if NDT > 0 160 DT_ENTER(profile, NULL); 161 if (CPU_IS_PRIMARY(ci)) 162 DT_ENTER(interval, NULL); 163 #endif 164 165 /* 166 * If we are not the primary CPU, we're not allowed to do 167 * any more work. 168 */ 169 if (CPU_IS_PRIMARY(ci) == 0) 170 return; 171 172 tc_ticktock(); 173 ticks++; 174 jiffies++; 175 176 /* 177 * Update the timeout wheel. 178 */ 179 timeout_hardclock_update(); 180 } 181 182 /* 183 * Compute number of hz in the specified amount of time. 184 */ 185 int 186 tvtohz(const struct timeval *tv) 187 { 188 unsigned long nticks; 189 time_t sec; 190 long usec; 191 192 /* 193 * If the number of usecs in the whole seconds part of the time 194 * fits in a long, then the total number of usecs will 195 * fit in an unsigned long. Compute the total and convert it to 196 * ticks, rounding up and adding 1 to allow for the current tick 197 * to expire. Rounding also depends on unsigned long arithmetic 198 * to avoid overflow. 199 * 200 * Otherwise, if the number of ticks in the whole seconds part of 201 * the time fits in a long, then convert the parts to 202 * ticks separately and add, using similar rounding methods and 203 * overflow avoidance. This method would work in the previous 204 * case but it is slightly slower and assumes that hz is integral. 205 * 206 * Otherwise, round the time down to the maximum 207 * representable value. 208 * 209 * If ints have 32 bits, then the maximum value for any timeout in 210 * 10ms ticks is 248 days. 211 */ 212 sec = tv->tv_sec; 213 usec = tv->tv_usec; 214 if (sec < 0 || (sec == 0 && usec <= 0)) 215 nticks = 0; 216 else if (sec <= LONG_MAX / 1000000) 217 nticks = (sec * 1000000 + (unsigned long)usec + (tick - 1)) 218 / tick + 1; 219 else if (sec <= LONG_MAX / hz) 220 nticks = sec * hz 221 + ((unsigned long)usec + (tick - 1)) / tick + 1; 222 else 223 nticks = LONG_MAX; 224 if (nticks > INT_MAX) 225 nticks = INT_MAX; 226 return ((int)nticks); 227 } 228 229 int 230 tstohz(const struct timespec *ts) 231 { 232 struct timeval tv; 233 TIMESPEC_TO_TIMEVAL(&tv, ts); 234 235 /* Round up. */ 236 if ((ts->tv_nsec % 1000) != 0) { 237 tv.tv_usec += 1; 238 if (tv.tv_usec >= 1000000) { 239 tv.tv_usec -= 1000000; 240 tv.tv_sec += 1; 241 } 242 } 243 244 return (tvtohz(&tv)); 245 } 246 247 /* 248 * Start profiling on a process. 249 * 250 * Kernel profiling passes proc0 which never exits and hence 251 * keeps the profile clock running constantly. 252 */ 253 void 254 startprofclock(struct process *pr) 255 { 256 int s; 257 258 if ((pr->ps_flags & PS_PROFIL) == 0) { 259 atomic_setbits_int(&pr->ps_flags, PS_PROFIL); 260 if (++profprocs == 1) { 261 s = splstatclock(); 262 psdiv = pscnt = psratio; 263 setstatclockrate(profhz); 264 splx(s); 265 } 266 } 267 } 268 269 /* 270 * Stop profiling on a process. 271 */ 272 void 273 stopprofclock(struct process *pr) 274 { 275 int s; 276 277 if (pr->ps_flags & PS_PROFIL) { 278 atomic_clearbits_int(&pr->ps_flags, PS_PROFIL); 279 if (--profprocs == 0) { 280 s = splstatclock(); 281 psdiv = pscnt = 1; 282 setstatclockrate(stathz); 283 splx(s); 284 } 285 } 286 } 287 288 /* 289 * Statistics clock. Grab profile sample, and if divider reaches 0, 290 * do process and kernel statistics. 291 */ 292 void 293 statclock(struct clockframe *frame) 294 { 295 #if defined(GPROF) || defined(DDBPROF) 296 struct gmonparam *g; 297 u_long i; 298 #endif 299 struct cpu_info *ci = curcpu(); 300 struct schedstate_percpu *spc = &ci->ci_schedstate; 301 struct proc *p = curproc; 302 struct process *pr; 303 304 /* 305 * Notice changes in divisor frequency, and adjust clock 306 * frequency accordingly. 307 */ 308 if (spc->spc_psdiv != psdiv) { 309 spc->spc_psdiv = psdiv; 310 spc->spc_pscnt = psdiv; 311 if (psdiv == 1) { 312 setstatclockrate(stathz); 313 } else { 314 setstatclockrate(profhz); 315 } 316 } 317 318 if (CLKF_USERMODE(frame)) { 319 pr = p->p_p; 320 if (pr->ps_flags & PS_PROFIL) 321 addupc_intr(p, CLKF_PC(frame)); 322 if (--spc->spc_pscnt > 0) 323 return; 324 /* 325 * Came from user mode; CPU was in user state. 326 * If this process is being profiled record the tick. 327 */ 328 p->p_uticks++; 329 if (pr->ps_nice > NZERO) 330 spc->spc_cp_time[CP_NICE]++; 331 else 332 spc->spc_cp_time[CP_USER]++; 333 } else { 334 #if defined(GPROF) || defined(DDBPROF) 335 /* 336 * Kernel statistics are just like addupc_intr, only easier. 337 */ 338 g = ci->ci_gmon; 339 if (g != NULL && g->state == GMON_PROF_ON) { 340 i = CLKF_PC(frame) - g->lowpc; 341 if (i < g->textsize) { 342 i /= HISTFRACTION * sizeof(*g->kcount); 343 g->kcount[i]++; 344 } 345 } 346 #endif 347 if (p != NULL && p->p_p->ps_flags & PS_PROFIL) 348 addupc_intr(p, PROC_PC(p)); 349 if (--spc->spc_pscnt > 0) 350 return; 351 /* 352 * Came from kernel mode, so we were: 353 * - spinning on a lock 354 * - handling an interrupt, 355 * - doing syscall or trap work on behalf of the current 356 * user process, or 357 * - spinning in the idle loop. 358 * Whichever it is, charge the time as appropriate. 359 * Note that we charge interrupts to the current process, 360 * regardless of whether they are ``for'' that process, 361 * so that we know how much of its real time was spent 362 * in ``non-process'' (i.e., interrupt) work. 363 */ 364 if (CLKF_INTR(frame)) { 365 if (p != NULL) 366 p->p_iticks++; 367 spc->spc_cp_time[spc->spc_spinning ? 368 CP_SPIN : CP_INTR]++; 369 } else if (p != NULL && p != spc->spc_idleproc) { 370 p->p_sticks++; 371 spc->spc_cp_time[spc->spc_spinning ? 372 CP_SPIN : CP_SYS]++; 373 } else 374 spc->spc_cp_time[spc->spc_spinning ? 375 CP_SPIN : CP_IDLE]++; 376 } 377 spc->spc_pscnt = psdiv; 378 379 if (p != NULL) { 380 p->p_cpticks++; 381 /* 382 * If no schedclock is provided, call it here at ~~12-25 Hz; 383 * ~~16 Hz is best 384 */ 385 if (schedhz == 0) { 386 if ((++spc->spc_schedticks & 3) == 0) 387 schedclock(p); 388 } 389 } 390 } 391 392 /* 393 * Return information about system clocks. 394 */ 395 int 396 sysctl_clockrate(char *where, size_t *sizep, void *newp) 397 { 398 struct clockinfo clkinfo; 399 400 /* 401 * Construct clockinfo structure. 402 */ 403 memset(&clkinfo, 0, sizeof clkinfo); 404 clkinfo.tick = tick; 405 clkinfo.hz = hz; 406 clkinfo.profhz = profhz; 407 clkinfo.stathz = stathz; 408 return (sysctl_rdstruct(where, sizep, newp, &clkinfo, sizeof(clkinfo))); 409 } 410