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