1 /*- 2 * Copyright (c) 1982, 1986, 1993 3 * The Regents of the University of California. All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions 7 * are met: 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 3. All advertising materials mentioning features or use of this software 14 * must display the following acknowledgement: 15 * This product includes software developed by the University of 16 * California, Berkeley and its contributors. 17 * 4. Neither the name of the University nor the names of its contributors 18 * may be used to endorse or promote products derived from this software 19 * without specific prior written permission. 20 * 21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 * SUCH DAMAGE. 32 * 33 * @(#)subr_prof.c 8.3 (Berkeley) 9/23/93 34 * $FreeBSD$ 35 */ 36 37 #include <sys/param.h> 38 #include <sys/systm.h> 39 #include <sys/sysproto.h> 40 #include <sys/kernel.h> 41 #include <sys/lock.h> 42 #include <sys/mutex.h> 43 #include <sys/proc.h> 44 #include <sys/resourcevar.h> 45 #include <sys/sysctl.h> 46 47 #include <machine/cpu.h> 48 49 #ifdef GPROF 50 #include <sys/malloc.h> 51 #include <sys/gmon.h> 52 #undef MCOUNT 53 54 static MALLOC_DEFINE(M_GPROF, "gprof", "kernel profiling buffer"); 55 56 static void kmstartup(void *); 57 SYSINIT(kmem, SI_SUB_KPROF, SI_ORDER_FIRST, kmstartup, NULL) 58 59 struct gmonparam _gmonparam = { GMON_PROF_OFF }; 60 61 #ifdef GUPROF 62 #include <machine/asmacros.h> 63 64 void 65 nullfunc_loop_profiled() 66 { 67 int i; 68 69 for (i = 0; i < CALIB_SCALE; i++) 70 nullfunc_profiled(); 71 } 72 73 #define nullfunc_loop_profiled_end nullfunc_profiled /* XXX */ 74 75 void 76 nullfunc_profiled() 77 { 78 } 79 #endif /* GUPROF */ 80 81 /* 82 * Update the histograms to support extending the text region arbitrarily. 83 * This is done slightly naively (no sparse regions), so will waste slight 84 * amounts of memory, but will overall work nicely enough to allow profiling 85 * of KLDs. 86 */ 87 void 88 kmupetext(uintfptr_t nhighpc) 89 { 90 struct gmonparam np; /* slightly large */ 91 struct gmonparam *p = &_gmonparam; 92 char *cp; 93 94 GIANT_REQUIRED; 95 bcopy(p, &np, sizeof(*p)); 96 np.highpc = ROUNDUP(nhighpc, HISTFRACTION * sizeof(HISTCOUNTER)); 97 if (np.highpc <= p->highpc) 98 return; 99 np.textsize = np.highpc - p->lowpc; 100 np.kcountsize = np.textsize / HISTFRACTION; 101 np.hashfraction = HASHFRACTION; 102 np.fromssize = np.textsize / HASHFRACTION; 103 np.tolimit = np.textsize * ARCDENSITY / 100; 104 if (np.tolimit < MINARCS) 105 np.tolimit = MINARCS; 106 else if (np.tolimit > MAXARCS) 107 np.tolimit = MAXARCS; 108 np.tossize = np.tolimit * sizeof(struct tostruct); 109 cp = malloc(np.kcountsize + np.fromssize + np.tossize, 110 M_GPROF, M_WAITOK); 111 /* 112 * Check for something else extending highpc while we slept. 113 */ 114 if (np.highpc <= p->highpc) { 115 free(cp, M_GPROF); 116 return; 117 } 118 np.tos = (struct tostruct *)cp; 119 cp += np.tossize; 120 np.kcount = (HISTCOUNTER *)cp; 121 cp += np.kcountsize; 122 np.froms = (u_short *)cp; 123 #ifdef GUPROF 124 /* Reinitialize pointers to overhead counters. */ 125 np.cputime_count = &KCOUNT(&np, PC_TO_I(&np, cputime)); 126 np.mcount_count = &KCOUNT(&np, PC_TO_I(&np, mcount)); 127 np.mexitcount_count = &KCOUNT(&np, PC_TO_I(&np, mexitcount)); 128 #endif 129 critical_enter(); 130 bcopy(p->tos, np.tos, p->tossize); 131 bzero((char *)np.tos + p->tossize, np.tossize - p->tossize); 132 bcopy(p->kcount, np.kcount, p->kcountsize); 133 bzero((char *)np.kcount + p->kcountsize, np.kcountsize - 134 p->kcountsize); 135 bcopy(p->froms, np.froms, p->fromssize); 136 bzero((char *)np.froms + p->fromssize, np.fromssize - p->fromssize); 137 cp = (char *)p->tos; 138 bcopy(&np, p, sizeof(*p)); 139 critical_exit(); 140 free(cp, M_GPROF); 141 } 142 143 static void 144 kmstartup(dummy) 145 void *dummy; 146 { 147 char *cp; 148 struct gmonparam *p = &_gmonparam; 149 #ifdef GUPROF 150 int cputime_overhead; 151 int empty_loop_time; 152 int i; 153 int mcount_overhead; 154 int mexitcount_overhead; 155 int nullfunc_loop_overhead; 156 int nullfunc_loop_profiled_time; 157 uintfptr_t tmp_addr; 158 #endif 159 160 /* 161 * Round lowpc and highpc to multiples of the density we're using 162 * so the rest of the scaling (here and in gprof) stays in ints. 163 */ 164 p->lowpc = ROUNDDOWN((u_long)btext, HISTFRACTION * sizeof(HISTCOUNTER)); 165 p->highpc = ROUNDUP((u_long)etext, HISTFRACTION * sizeof(HISTCOUNTER)); 166 p->textsize = p->highpc - p->lowpc; 167 printf("Profiling kernel, textsize=%lu [%x..%x]\n", 168 p->textsize, p->lowpc, p->highpc); 169 p->kcountsize = p->textsize / HISTFRACTION; 170 p->hashfraction = HASHFRACTION; 171 p->fromssize = p->textsize / HASHFRACTION; 172 p->tolimit = p->textsize * ARCDENSITY / 100; 173 if (p->tolimit < MINARCS) 174 p->tolimit = MINARCS; 175 else if (p->tolimit > MAXARCS) 176 p->tolimit = MAXARCS; 177 p->tossize = p->tolimit * sizeof(struct tostruct); 178 cp = (char *)malloc(p->kcountsize + p->fromssize + p->tossize, 179 M_GPROF, M_WAITOK | M_ZERO); 180 p->tos = (struct tostruct *)cp; 181 cp += p->tossize; 182 p->kcount = (HISTCOUNTER *)cp; 183 cp += p->kcountsize; 184 p->froms = (u_short *)cp; 185 186 #ifdef GUPROF 187 /* Initialize pointers to overhead counters. */ 188 p->cputime_count = &KCOUNT(p, PC_TO_I(p, cputime)); 189 p->mcount_count = &KCOUNT(p, PC_TO_I(p, mcount)); 190 p->mexitcount_count = &KCOUNT(p, PC_TO_I(p, mexitcount)); 191 192 /* 193 * Disable interrupts to avoid interference while we calibrate 194 * things. 195 */ 196 critical_enter(); 197 198 /* 199 * Determine overheads. 200 * XXX this needs to be repeated for each useful timer/counter. 201 */ 202 cputime_overhead = 0; 203 startguprof(p); 204 for (i = 0; i < CALIB_SCALE; i++) 205 cputime_overhead += cputime(); 206 207 empty_loop(); 208 startguprof(p); 209 empty_loop(); 210 empty_loop_time = cputime(); 211 212 nullfunc_loop_profiled(); 213 214 /* 215 * Start profiling. There won't be any normal function calls since 216 * interrupts are disabled, but we will call the profiling routines 217 * directly to determine their overheads. 218 */ 219 p->state = GMON_PROF_HIRES; 220 221 startguprof(p); 222 nullfunc_loop_profiled(); 223 224 startguprof(p); 225 for (i = 0; i < CALIB_SCALE; i++) 226 #if defined(__i386__) && __GNUC__ >= 2 227 __asm("pushl %0; call __mcount; popl %%ecx" 228 : 229 : "i" (profil) 230 : "ax", "bx", "cx", "dx", "memory"); 231 #elif defined(lint) 232 #else 233 #error 234 #endif 235 mcount_overhead = KCOUNT(p, PC_TO_I(p, profil)); 236 237 startguprof(p); 238 for (i = 0; i < CALIB_SCALE; i++) 239 #if defined(__i386__) && __GNUC__ >= 2 240 __asm("call " __XSTRING(HIDENAME(mexitcount)) "; 1:" 241 : : : "ax", "bx", "cx", "dx", "memory"); 242 __asm("movl $1b,%0" : "=rm" (tmp_addr)); 243 #elif defined(lint) 244 #else 245 #error 246 #endif 247 mexitcount_overhead = KCOUNT(p, PC_TO_I(p, tmp_addr)); 248 249 p->state = GMON_PROF_OFF; 250 stopguprof(p); 251 252 critical_exit(); 253 254 nullfunc_loop_profiled_time = 0; 255 for (tmp_addr = (uintfptr_t)nullfunc_loop_profiled; 256 tmp_addr < (uintfptr_t)nullfunc_loop_profiled_end; 257 tmp_addr += HISTFRACTION * sizeof(HISTCOUNTER)) 258 nullfunc_loop_profiled_time += KCOUNT(p, PC_TO_I(p, tmp_addr)); 259 #define CALIB_DOSCALE(count) (((count) + CALIB_SCALE / 3) / CALIB_SCALE) 260 #define c2n(count, freq) ((int)((count) * 1000000000LL / freq)) 261 printf("cputime %d, empty_loop %d, nullfunc_loop_profiled %d, mcount %d, mexitcount %d\n", 262 CALIB_DOSCALE(c2n(cputime_overhead, p->profrate)), 263 CALIB_DOSCALE(c2n(empty_loop_time, p->profrate)), 264 CALIB_DOSCALE(c2n(nullfunc_loop_profiled_time, p->profrate)), 265 CALIB_DOSCALE(c2n(mcount_overhead, p->profrate)), 266 CALIB_DOSCALE(c2n(mexitcount_overhead, p->profrate))); 267 cputime_overhead -= empty_loop_time; 268 mcount_overhead -= empty_loop_time; 269 mexitcount_overhead -= empty_loop_time; 270 271 /*- 272 * Profiling overheads are determined by the times between the 273 * following events: 274 * MC1: mcount() is called 275 * MC2: cputime() (called from mcount()) latches the timer 276 * MC3: mcount() completes 277 * ME1: mexitcount() is called 278 * ME2: cputime() (called from mexitcount()) latches the timer 279 * ME3: mexitcount() completes. 280 * The times between the events vary slightly depending on instruction 281 * combination and cache misses, etc. Attempt to determine the 282 * minimum times. These can be subtracted from the profiling times 283 * without much risk of reducing the profiling times below what they 284 * would be when profiling is not configured. Abbreviate: 285 * ab = minimum time between MC1 and MC3 286 * a = minumum time between MC1 and MC2 287 * b = minimum time between MC2 and MC3 288 * cd = minimum time between ME1 and ME3 289 * c = minimum time between ME1 and ME2 290 * d = minimum time between ME2 and ME3. 291 * These satisfy the relations: 292 * ab <= mcount_overhead (just measured) 293 * a + b <= ab 294 * cd <= mexitcount_overhead (just measured) 295 * c + d <= cd 296 * a + d <= nullfunc_loop_profiled_time (just measured) 297 * a >= 0, b >= 0, c >= 0, d >= 0. 298 * Assume that ab and cd are equal to the minimums. 299 */ 300 p->cputime_overhead = CALIB_DOSCALE(cputime_overhead); 301 p->mcount_overhead = CALIB_DOSCALE(mcount_overhead - cputime_overhead); 302 p->mexitcount_overhead = CALIB_DOSCALE(mexitcount_overhead 303 - cputime_overhead); 304 nullfunc_loop_overhead = nullfunc_loop_profiled_time - empty_loop_time; 305 p->mexitcount_post_overhead = CALIB_DOSCALE((mcount_overhead 306 - nullfunc_loop_overhead) 307 / 4); 308 p->mexitcount_pre_overhead = p->mexitcount_overhead 309 + p->cputime_overhead 310 - p->mexitcount_post_overhead; 311 p->mcount_pre_overhead = CALIB_DOSCALE(nullfunc_loop_overhead) 312 - p->mexitcount_post_overhead; 313 p->mcount_post_overhead = p->mcount_overhead 314 + p->cputime_overhead 315 - p->mcount_pre_overhead; 316 printf( 317 "Profiling overheads: mcount: %d+%d, %d+%d; mexitcount: %d+%d, %d+%d nsec\n", 318 c2n(p->cputime_overhead, p->profrate), 319 c2n(p->mcount_overhead, p->profrate), 320 c2n(p->mcount_pre_overhead, p->profrate), 321 c2n(p->mcount_post_overhead, p->profrate), 322 c2n(p->cputime_overhead, p->profrate), 323 c2n(p->mexitcount_overhead, p->profrate), 324 c2n(p->mexitcount_pre_overhead, p->profrate), 325 c2n(p->mexitcount_post_overhead, p->profrate)); 326 printf( 327 "Profiling overheads: mcount: %d+%d, %d+%d; mexitcount: %d+%d, %d+%d cycles\n", 328 p->cputime_overhead, p->mcount_overhead, 329 p->mcount_pre_overhead, p->mcount_post_overhead, 330 p->cputime_overhead, p->mexitcount_overhead, 331 p->mexitcount_pre_overhead, p->mexitcount_post_overhead); 332 #endif /* GUPROF */ 333 } 334 335 /* 336 * Return kernel profiling information. 337 */ 338 static int 339 sysctl_kern_prof(SYSCTL_HANDLER_ARGS) 340 { 341 int *name = (int *) arg1; 342 u_int namelen = arg2; 343 struct gmonparam *gp = &_gmonparam; 344 int error; 345 int state; 346 347 /* all sysctl names at this level are terminal */ 348 if (namelen != 1) 349 return (ENOTDIR); /* overloaded */ 350 351 switch (name[0]) { 352 case GPROF_STATE: 353 state = gp->state; 354 error = sysctl_handle_int(oidp, &state, 0, req); 355 if (error) 356 return (error); 357 if (!req->newptr) 358 return (0); 359 if (state == GMON_PROF_OFF) { 360 gp->state = state; 361 PROC_LOCK(&proc0); 362 stopprofclock(&proc0); 363 PROC_UNLOCK(&proc0); 364 stopguprof(gp); 365 } else if (state == GMON_PROF_ON) { 366 gp->state = GMON_PROF_OFF; 367 stopguprof(gp); 368 gp->profrate = profhz; 369 startprofclock(&proc0); 370 gp->state = state; 371 #ifdef GUPROF 372 } else if (state == GMON_PROF_HIRES) { 373 gp->state = GMON_PROF_OFF; 374 PROC_LOCK(&proc0); 375 stopprofclock(&proc0); 376 PROC_UNLOCK(&proc0); 377 startguprof(gp); 378 gp->state = state; 379 #endif 380 } else if (state != gp->state) 381 return (EINVAL); 382 return (0); 383 case GPROF_COUNT: 384 return (sysctl_handle_opaque(oidp, 385 gp->kcount, gp->kcountsize, req)); 386 case GPROF_FROMS: 387 return (sysctl_handle_opaque(oidp, 388 gp->froms, gp->fromssize, req)); 389 case GPROF_TOS: 390 return (sysctl_handle_opaque(oidp, 391 gp->tos, gp->tossize, req)); 392 case GPROF_GMONPARAM: 393 return (sysctl_handle_opaque(oidp, gp, sizeof *gp, req)); 394 default: 395 return (EOPNOTSUPP); 396 } 397 /* NOTREACHED */ 398 } 399 400 SYSCTL_NODE(_kern, KERN_PROF, prof, CTLFLAG_RW, sysctl_kern_prof, ""); 401 #endif /* GPROF */ 402 403 /* 404 * Profiling system call. 405 * 406 * The scale factor is a fixed point number with 16 bits of fraction, so that 407 * 1.0 is represented as 0x10000. A scale factor of 0 turns off profiling. 408 */ 409 #ifndef _SYS_SYSPROTO_H_ 410 struct profil_args { 411 caddr_t samples; 412 size_t size; 413 size_t offset; 414 u_int scale; 415 }; 416 #endif 417 /* 418 * MPSAFE 419 */ 420 /* ARGSUSED */ 421 int 422 profil(td, uap) 423 struct thread *td; 424 register struct profil_args *uap; 425 { 426 struct uprof *upp; 427 int s; 428 int error = 0; 429 430 mtx_lock(&Giant); 431 432 if (uap->scale > (1 << 16)) { 433 error = EINVAL; 434 goto done2; 435 } 436 if (uap->scale == 0) { 437 PROC_LOCK(td->td_proc); 438 stopprofclock(td->td_proc); 439 PROC_UNLOCK(td->td_proc); 440 goto done2; 441 } 442 upp = &td->td_proc->p_stats->p_prof; 443 444 /* Block profile interrupts while changing state. */ 445 s = splstatclock(); 446 upp->pr_off = uap->offset; 447 upp->pr_scale = uap->scale; 448 upp->pr_base = uap->samples; 449 upp->pr_size = uap->size; 450 startprofclock(td->td_proc); 451 splx(s); 452 453 done2: 454 mtx_unlock(&Giant); 455 return (error); 456 } 457 458 /* 459 * Scale is a fixed-point number with the binary point 16 bits 460 * into the value, and is <= 1.0. pc is at most 32 bits, so the 461 * intermediate result is at most 48 bits. 462 */ 463 #define PC_TO_INDEX(pc, prof) \ 464 ((int)(((u_quad_t)((pc) - (prof)->pr_off) * \ 465 (u_quad_t)((prof)->pr_scale)) >> 16) & ~1) 466 467 /* 468 * Collect user-level profiling statistics; called on a profiling tick, 469 * when a process is running in user-mode. This routine may be called 470 * from an interrupt context. We try to update the user profiling buffers 471 * cheaply with fuswintr() and suswintr(). If that fails, we revert to 472 * an AST that will vector us to trap() with a context in which copyin 473 * and copyout will work. Trap will then call addupc_task(). 474 * 475 * Note that we may (rarely) not get around to the AST soon enough, and 476 * lose profile ticks when the next tick overwrites this one, but in this 477 * case the system is overloaded and the profile is probably already 478 * inaccurate. 479 */ 480 void 481 addupc_intr(struct thread *td, uintptr_t pc, u_int ticks) 482 { 483 struct uprof *prof; 484 caddr_t addr; 485 u_int i; 486 int v; 487 488 if (ticks == 0) 489 return; 490 prof = &td->td_proc->p_stats->p_prof; 491 if (pc < prof->pr_off || 492 (i = PC_TO_INDEX(pc, prof)) >= prof->pr_size) 493 return; /* out of range; ignore */ 494 495 addr = prof->pr_base + i; 496 if ((v = fuswintr(addr)) == -1 || suswintr(addr, v + ticks) == -1) { 497 mtx_lock_spin(&sched_lock); 498 prof->pr_addr = pc; 499 prof->pr_ticks = ticks; 500 td->td_flags |= TDF_OWEUPC | TDF_ASTPENDING ; 501 mtx_unlock_spin(&sched_lock); 502 } 503 } 504 505 /* 506 * Much like before, but we can afford to take faults here. If the 507 * update fails, we simply turn off profiling. 508 * XXXKSE, don't use kse unless we got sched lock. 509 */ 510 void 511 addupc_task(struct thread *td, uintptr_t pc, u_int ticks) 512 { 513 struct proc *p = td->td_proc; 514 struct uprof *prof; 515 caddr_t addr; 516 u_int i; 517 u_short v; 518 int stop = 0; 519 520 if (ticks == 0) 521 return; 522 523 PROC_LOCK(p); 524 mtx_lock_spin(&sched_lock); 525 if (!(p->p_sflag & PS_PROFIL)) { 526 mtx_unlock_spin(&sched_lock); 527 PROC_UNLOCK(p); 528 return; 529 } 530 p->p_profthreads++; 531 mtx_unlock_spin(&sched_lock); 532 PROC_UNLOCK(p); 533 prof = &p->p_stats->p_prof; 534 if (pc < prof->pr_off || 535 (i = PC_TO_INDEX(pc, prof)) >= prof->pr_size) { 536 goto out; 537 } 538 539 addr = prof->pr_base + i; 540 if (copyin(addr, &v, sizeof(v)) == 0) { 541 v += ticks; 542 if (copyout(&v, addr, sizeof(v)) == 0) 543 goto out; 544 } 545 stop = 1; 546 547 out: 548 PROC_LOCK(p); 549 if (--p->p_profthreads == 0) { 550 if (p->p_sflag & PS_STOPPROF) { 551 wakeup(&p->p_profthreads); 552 stop = 0; 553 } 554 } 555 if (stop) 556 stopprofclock(p); 557 PROC_UNLOCK(p); 558 } 559 560 #if defined(__i386__) && __GNUC__ >= 2 561 /* 562 * Support for "--test-coverage --profile-arcs" in GCC. 563 * 564 * We need to call all the functions in the .ctor section, in order 565 * to get all the counter-arrays strung into a list. 566 * 567 * XXX: the .ctors call __bb_init_func which is located in over in 568 * XXX: i386/i386/support.s for historical reasons. There is probably 569 * XXX: no reason for that to be assembler anymore, but doing it right 570 * XXX: in MI C code requires one to reverse-engineer the type-selection 571 * XXX: inside GCC. Have fun. 572 * 573 * XXX: Worrisome perspective: Calling the .ctors may make C++ in the 574 * XXX: kernel feasible. Don't. 575 */ 576 typedef void (*ctor_t)(void); 577 extern ctor_t _start_ctors, _stop_ctors; 578 579 static void 580 tcov_init(void *foo __unused) 581 { 582 ctor_t *p, q; 583 584 for (p = &_start_ctors; p < &_stop_ctors; p++) { 585 q = *p; 586 q(); 587 } 588 } 589 590 SYSINIT(tcov_init, SI_SUB_KPROF, SI_ORDER_SECOND, tcov_init, NULL) 591 592 /* 593 * GCC contains magic to recognize calls to for instance execve() and 594 * puts in calls to this function to preserve the profile counters. 595 * XXX: Put zinging punchline here. 596 */ 597 void __bb_fork_func(void); 598 void 599 __bb_fork_func(void) 600 { 601 } 602 603 #endif 604 605