FreeBSD/Linux Kernel Cross Reference
sys/kern/subr_prof.c
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: releng/5.0/sys/kern/subr_prof.c 104285 2002-10-01 13:15:11Z phk $
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 stopprofclock(&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 startprofclock(&proc0);
368 gp->state = state;
369 #ifdef GUPROF
370 } else if (state == GMON_PROF_HIRES) {
371 gp->state = GMON_PROF_OFF;
372 stopprofclock(&proc0);
373 startguprof(gp);
374 gp->state = state;
375 #endif
376 } else if (state != gp->state)
377 return (EINVAL);
378 return (0);
379 case GPROF_COUNT:
380 return (sysctl_handle_opaque(oidp,
381 gp->kcount, gp->kcountsize, req));
382 case GPROF_FROMS:
383 return (sysctl_handle_opaque(oidp,
384 gp->froms, gp->fromssize, req));
385 case GPROF_TOS:
386 return (sysctl_handle_opaque(oidp,
387 gp->tos, gp->tossize, req));
388 case GPROF_GMONPARAM:
389 return (sysctl_handle_opaque(oidp, gp, sizeof *gp, req));
390 default:
391 return (EOPNOTSUPP);
392 }
393 /* NOTREACHED */
394 }
395
396 SYSCTL_NODE(_kern, KERN_PROF, prof, CTLFLAG_RW, sysctl_kern_prof, "");
397 #endif /* GPROF */
398
399 /*
400 * Profiling system call.
401 *
402 * The scale factor is a fixed point number with 16 bits of fraction, so that
403 * 1.0 is represented as 0x10000. A scale factor of 0 turns off profiling.
404 */
405 #ifndef _SYS_SYSPROTO_H_
406 struct profil_args {
407 caddr_t samples;
408 size_t size;
409 size_t offset;
410 u_int scale;
411 };
412 #endif
413 /*
414 * MPSAFE
415 */
416 /* ARGSUSED */
417 int
418 profil(td, uap)
419 struct thread *td;
420 register struct profil_args *uap;
421 {
422 register struct uprof *upp;
423 int s;
424 int error = 0;
425
426 mtx_lock(&Giant);
427
428 if (uap->scale > (1 << 16)) {
429 error = EINVAL;
430 goto done2;
431 }
432 if (uap->scale == 0) {
433 stopprofclock(td->td_proc);
434 goto done2;
435 }
436 upp = &td->td_proc->p_stats->p_prof;
437
438 /* Block profile interrupts while changing state. */
439 s = splstatclock();
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 startprofclock(td->td_proc);
445 splx(s);
446
447 done2:
448 mtx_unlock(&Giant);
449 return (error);
450 }
451
452 /*
453 * Scale is a fixed-point number with the binary point 16 bits
454 * into the value, and is <= 1.0. pc is at most 32 bits, so the
455 * intermediate result is at most 48 bits.
456 */
457 #define PC_TO_INDEX(pc, prof) \
458 ((int)(((u_quad_t)((pc) - (prof)->pr_off) * \
459 (u_quad_t)((prof)->pr_scale)) >> 16) & ~1)
460
461 /*
462 * Collect user-level profiling statistics; called on a profiling tick,
463 * when a process is running in user-mode. This routine may be called
464 * from an interrupt context. We try to update the user profiling buffers
465 * cheaply with fuswintr() and suswintr(). If that fails, we revert to
466 * an AST that will vector us to trap() with a context in which copyin
467 * and copyout will work. Trap will then call addupc_task().
468 *
469 * Note that we may (rarely) not get around to the AST soon enough, and
470 * lose profile ticks when the next tick overwrites this one, but in this
471 * case the system is overloaded and the profile is probably already
472 * inaccurate.
473 */
474 void
475 addupc_intr(ke, pc, ticks)
476 register struct kse *ke;
477 register uintptr_t pc;
478 u_int ticks;
479 {
480 register struct uprof *prof;
481 register caddr_t addr;
482 register u_int i;
483 register int v;
484
485 if (ticks == 0)
486 return;
487 prof = &ke->ke_proc->p_stats->p_prof;
488 if (pc < prof->pr_off ||
489 (i = PC_TO_INDEX(pc, prof)) >= prof->pr_size)
490 return; /* out of range; ignore */
491
492 addr = prof->pr_base + i;
493 if ((v = fuswintr(addr)) == -1 || suswintr(addr, v + ticks) == -1) {
494 mtx_lock_spin(&sched_lock);
495 prof->pr_addr = pc;
496 prof->pr_ticks = ticks;
497 ke->ke_flags |= KEF_OWEUPC | KEF_ASTPENDING ;
498 mtx_unlock_spin(&sched_lock);
499 }
500 }
501
502 /*
503 * Much like before, but we can afford to take faults here. If the
504 * update fails, we simply turn off profiling.
505 */
506 void
507 addupc_task(ke, pc, ticks)
508 register struct kse *ke;
509 register uintptr_t pc;
510 u_int ticks;
511 {
512 struct proc *p = ke->ke_proc;
513 register struct uprof *prof;
514 register caddr_t addr;
515 register u_int i;
516 u_short v;
517
518 if (ticks == 0)
519 return;
520
521 prof = &p->p_stats->p_prof;
522 if (pc < prof->pr_off ||
523 (i = PC_TO_INDEX(pc, prof)) >= prof->pr_size)
524 return;
525
526 addr = prof->pr_base + i;
527 if (copyin(addr, &v, sizeof(v)) == 0) {
528 v += ticks;
529 if (copyout(&v, addr, sizeof(v)) == 0)
530 return;
531 }
532 stopprofclock(p);
533 }
Cache object: 42e8e10cf23d6858c4dec65a3b7e4a8f
|