xref: /freebsd/sys/kern/subr_prof.c (revision a8445737e740901f5f2c8d24c12ef7fc8b00134e)
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  * $Id: subr_prof.c,v 1.27 1998/07/14 05:09:46 bde Exp $
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/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 
51 static MALLOC_DEFINE(M_GPROF, "gprof", "kernel profiling buffer");
52 
53 static void kmstartup __P((void *));
54 SYSINIT(kmem, SI_SUB_KPROF, SI_ORDER_FIRST, kmstartup, NULL)
55 
56 struct gmonparam _gmonparam = { GMON_PROF_OFF };
57 
58 #ifdef GUPROF
59 void
60 nullfunc_loop_profiled()
61 {
62 	int i;
63 
64 	for (i = 0; i < CALIB_SCALE; i++)
65 		nullfunc_profiled();
66 }
67 
68 #define	nullfunc_loop_profiled_end	nullfunc_profiled	/* XXX */
69 
70 void
71 nullfunc_profiled()
72 {
73 }
74 #endif /* GUPROF */
75 
76 static void
77 kmstartup(dummy)
78 	void *dummy;
79 {
80 	char *cp;
81 	struct gmonparam *p = &_gmonparam;
82 #ifdef GUPROF
83 	int cputime_overhead;
84 	int empty_loop_time;
85 	int i;
86 	int mcount_overhead;
87 	int mexitcount_overhead;
88 	int nullfunc_loop_overhead;
89 	int nullfunc_loop_profiled_time;
90 	uintfptr_t tmp_addr;
91 #endif
92 
93 	/*
94 	 * Round lowpc and highpc to multiples of the density we're using
95 	 * so the rest of the scaling (here and in gprof) stays in ints.
96 	 */
97 	p->lowpc = ROUNDDOWN((u_long)btext, HISTFRACTION * sizeof(HISTCOUNTER));
98 	p->highpc = ROUNDUP((u_long)etext, HISTFRACTION * sizeof(HISTCOUNTER));
99 	p->textsize = p->highpc - p->lowpc;
100 	printf("Profiling kernel, textsize=%lu [%x..%x]\n",
101 	       p->textsize, p->lowpc, p->highpc);
102 	p->kcountsize = p->textsize / HISTFRACTION;
103 	p->hashfraction = HASHFRACTION;
104 	p->fromssize = p->textsize / HASHFRACTION;
105 	p->tolimit = p->textsize * ARCDENSITY / 100;
106 	if (p->tolimit < MINARCS)
107 		p->tolimit = MINARCS;
108 	else if (p->tolimit > MAXARCS)
109 		p->tolimit = MAXARCS;
110 	p->tossize = p->tolimit * sizeof(struct tostruct);
111 	cp = (char *)malloc(p->kcountsize + p->fromssize + p->tossize,
112 	    M_GPROF, M_NOWAIT);
113 	if (cp == 0) {
114 		printf("No memory for profiling.\n");
115 		return;
116 	}
117 	bzero(cp, p->kcountsize + p->tossize + p->fromssize);
118 	p->tos = (struct tostruct *)cp;
119 	cp += p->tossize;
120 	p->kcount = (HISTCOUNTER *)cp;
121 	cp += p->kcountsize;
122 	p->froms = (u_short *)cp;
123 
124 #ifdef GUPROF
125 	/* Initialize pointers to overhead counters. */
126 	p->cputime_count = &KCOUNT(p, PC_TO_I(p, cputime));
127 	p->mcount_count = &KCOUNT(p, PC_TO_I(p, mcount));
128 	p->mexitcount_count = &KCOUNT(p, PC_TO_I(p, mexitcount));
129 
130 	/*
131 	 * Disable interrupts to avoid interference while we calibrate
132 	 * things.
133 	 */
134 	disable_intr();
135 
136 	/*
137 	 * Determine overheads.
138 	 * XXX this needs to be repeated for each useful timer/counter.
139 	 */
140 	cputime_overhead = 0;
141 	startguprof(p);
142 	for (i = 0; i < CALIB_SCALE; i++)
143 		cputime_overhead += cputime();
144 
145 	empty_loop();
146 	startguprof(p);
147 	empty_loop();
148 	empty_loop_time = cputime();
149 
150 	nullfunc_loop_profiled();
151 
152 	/*
153 	 * Start profiling.  There won't be any normal function calls since
154 	 * interrupts are disabled, but we will call the profiling routines
155 	 * directly to determine their overheads.
156 	 */
157 	p->state = GMON_PROF_HIRES;
158 
159 	startguprof(p);
160 	nullfunc_loop_profiled();
161 
162 	startguprof(p);
163 	for (i = 0; i < CALIB_SCALE; i++)
164 #if defined(__i386__) && __GNUC__ >= 2
165 		__asm("pushl %0; call __mcount; popl %%ecx"
166 		      :
167 		      : "i" (profil)
168 		      : "ax", "bx", "cx", "dx", "memory");
169 #else
170 #error
171 #endif
172 	mcount_overhead = KCOUNT(p, PC_TO_I(p, profil));
173 
174 	startguprof(p);
175 	for (i = 0; i < CALIB_SCALE; i++)
176 #if defined(__i386__) && __GNUC__ >= 2
177 		    __asm("call mexitcount; 1:"
178 			  : : : "ax", "bx", "cx", "dx", "memory");
179 	__asm("movl $1b,%0" : "=rm" (tmp_addr));
180 #else
181 #error
182 #endif
183 	mexitcount_overhead = KCOUNT(p, PC_TO_I(p, tmp_addr));
184 
185 	p->state = GMON_PROF_OFF;
186 	stopguprof(p);
187 
188 	enable_intr();
189 
190 	nullfunc_loop_profiled_time = 0;
191 	for (tmp_addr = (uintfptr_t)nullfunc_loop_profiled;
192 	     tmp_addr < (uintfptr_t)nullfunc_loop_profiled_end;
193 	     tmp_addr += HISTFRACTION * sizeof(HISTCOUNTER))
194 		nullfunc_loop_profiled_time += KCOUNT(p, PC_TO_I(p, tmp_addr));
195 #define CALIB_DOSCALE(count)	(((count) + CALIB_SCALE / 3) / CALIB_SCALE)
196 #define	c2n(count, freq)	((int)((count) * 1000000000LL / freq))
197 	printf("cputime %d, empty_loop %d, nullfunc_loop_profiled %d, mcount %d, mexitcount %d\n",
198 	       CALIB_DOSCALE(c2n(cputime_overhead, p->profrate)),
199 	       CALIB_DOSCALE(c2n(empty_loop_time, p->profrate)),
200 	       CALIB_DOSCALE(c2n(nullfunc_loop_profiled_time, p->profrate)),
201 	       CALIB_DOSCALE(c2n(mcount_overhead, p->profrate)),
202 	       CALIB_DOSCALE(c2n(mexitcount_overhead, p->profrate)));
203 	cputime_overhead -= empty_loop_time;
204 	mcount_overhead -= empty_loop_time;
205 	mexitcount_overhead -= empty_loop_time;
206 
207 	/*-
208 	 * Profiling overheads are determined by the times between the
209 	 * following events:
210 	 *	MC1: mcount() is called
211 	 *	MC2: cputime() (called from mcount()) latches the timer
212 	 *	MC3: mcount() completes
213 	 *	ME1: mexitcount() is called
214 	 *	ME2: cputime() (called from mexitcount()) latches the timer
215 	 *	ME3: mexitcount() completes.
216 	 * The times between the events vary slightly depending on instruction
217 	 * combination and cache misses, etc.  Attempt to determine the
218 	 * minimum times.  These can be subtracted from the profiling times
219 	 * without much risk of reducing the profiling times below what they
220 	 * would be when profiling is not configured.  Abbreviate:
221 	 *	ab = minimum time between MC1 and MC3
222 	 *	a  = minumum time between MC1 and MC2
223 	 *	b  = minimum time between MC2 and MC3
224 	 *	cd = minimum time between ME1 and ME3
225 	 *	c  = minimum time between ME1 and ME2
226 	 *	d  = minimum time between ME2 and ME3.
227 	 * These satisfy the relations:
228 	 *	ab            <= mcount_overhead		(just measured)
229 	 *	a + b         <= ab
230 	 *	        cd    <= mexitcount_overhead		(just measured)
231 	 *	        c + d <= cd
232 	 *	a         + d <= nullfunc_loop_profiled_time	(just measured)
233 	 *	a >= 0, b >= 0, c >= 0, d >= 0.
234 	 * Assume that ab and cd are equal to the minimums.
235 	 */
236 	p->cputime_overhead = CALIB_DOSCALE(cputime_overhead);
237 	p->mcount_overhead = CALIB_DOSCALE(mcount_overhead - cputime_overhead);
238 	p->mexitcount_overhead = CALIB_DOSCALE(mexitcount_overhead
239 					       - cputime_overhead);
240 	nullfunc_loop_overhead = nullfunc_loop_profiled_time - empty_loop_time;
241 	p->mexitcount_post_overhead = CALIB_DOSCALE((mcount_overhead
242 						     - nullfunc_loop_overhead)
243 						    / 4);
244 	p->mexitcount_pre_overhead = p->mexitcount_overhead
245 				     + p->cputime_overhead
246 				     - p->mexitcount_post_overhead;
247 	p->mcount_pre_overhead = CALIB_DOSCALE(nullfunc_loop_overhead)
248 				 - p->mexitcount_post_overhead;
249 	p->mcount_post_overhead = p->mcount_overhead
250 				  + p->cputime_overhead
251 				  - p->mcount_pre_overhead;
252 	printf(
253 "Profiling overheads: mcount: %d+%d, %d+%d; mexitcount: %d+%d, %d+%d nsec\n",
254 	       c2n(p->cputime_overhead, p->profrate),
255 	       c2n(p->mcount_overhead, p->profrate),
256 	       c2n(p->mcount_pre_overhead, p->profrate),
257 	       c2n(p->mcount_post_overhead, p->profrate),
258 	       c2n(p->cputime_overhead, p->profrate),
259 	       c2n(p->mexitcount_overhead, p->profrate),
260 	       c2n(p->mexitcount_pre_overhead, p->profrate),
261 	       c2n(p->mexitcount_post_overhead, p->profrate));
262 	printf(
263 "Profiling overheads: mcount: %d+%d, %d+%d; mexitcount: %d+%d, %d+%d cycles\n",
264 	       p->cputime_overhead, p->mcount_overhead,
265 	       p->mcount_pre_overhead, p->mcount_post_overhead,
266 	       p->cputime_overhead, p->mexitcount_overhead,
267 	       p->mexitcount_pre_overhead, p->mexitcount_post_overhead);
268 #endif /* GUPROF */
269 }
270 
271 /*
272  * Return kernel profiling information.
273  */
274 static int
275 sysctl_kern_prof SYSCTL_HANDLER_ARGS
276 {
277 	int *name = (int *) arg1;
278 	u_int namelen = arg2;
279 	struct gmonparam *gp = &_gmonparam;
280 	int error;
281 	int state;
282 
283 	/* all sysctl names at this level are terminal */
284 	if (namelen != 1)
285 		return (ENOTDIR);		/* overloaded */
286 
287 	switch (name[0]) {
288 	case GPROF_STATE:
289 		state = gp->state;
290 		error = sysctl_handle_int(oidp, &state, 0, req);
291 		if (error)
292 			return (error);
293 		if (!req->newptr)
294 			return (0);
295 		if (state == GMON_PROF_OFF) {
296 			gp->state = state;
297 			stopprofclock(&proc0);
298 			stopguprof(gp);
299 		} else if (state == GMON_PROF_ON) {
300 			gp->state = GMON_PROF_OFF;
301 			stopguprof(gp);
302 			gp->profrate = profhz;
303 			startprofclock(&proc0);
304 			gp->state = state;
305 #ifdef GUPROF
306 		} else if (state == GMON_PROF_HIRES) {
307 			gp->state = GMON_PROF_OFF;
308 			stopprofclock(&proc0);
309 			startguprof(gp);
310 			gp->state = state;
311 #endif
312 		} else if (state != gp->state)
313 			return (EINVAL);
314 		return (0);
315 	case GPROF_COUNT:
316 		return (sysctl_handle_opaque(oidp,
317 			gp->kcount, gp->kcountsize, req));
318 	case GPROF_FROMS:
319 		return (sysctl_handle_opaque(oidp,
320 			gp->froms, gp->fromssize, req));
321 	case GPROF_TOS:
322 		return (sysctl_handle_opaque(oidp,
323 			gp->tos, gp->tossize, req));
324 	case GPROF_GMONPARAM:
325 		return (sysctl_handle_opaque(oidp, gp, sizeof *gp, req));
326 	default:
327 		return (EOPNOTSUPP);
328 	}
329 	/* NOTREACHED */
330 }
331 
332 SYSCTL_NODE(_kern, KERN_PROF, prof, CTLFLAG_RW, sysctl_kern_prof, "");
333 #endif /* GPROF */
334 
335 /*
336  * Profiling system call.
337  *
338  * The scale factor is a fixed point number with 16 bits of fraction, so that
339  * 1.0 is represented as 0x10000.  A scale factor of 0 turns off profiling.
340  */
341 #ifndef _SYS_SYSPROTO_H_
342 struct profil_args {
343 	caddr_t	samples;
344 	size_t	size;
345 	size_t	offset;
346 	u_int	scale;
347 };
348 #endif
349 /* ARGSUSED */
350 int
351 profil(p, uap)
352 	struct proc *p;
353 	register struct profil_args *uap;
354 {
355 	register struct uprof *upp;
356 	int s;
357 
358 	if (uap->scale > (1 << 16))
359 		return (EINVAL);
360 	if (uap->scale == 0) {
361 		stopprofclock(p);
362 		return (0);
363 	}
364 	upp = &p->p_stats->p_prof;
365 
366 	/* Block profile interrupts while changing state. */
367 	s = splstatclock();
368 	upp->pr_off = uap->offset;
369 	upp->pr_scale = uap->scale;
370 	upp->pr_base = uap->samples;
371 	upp->pr_size = uap->size;
372 	startprofclock(p);
373 	splx(s);
374 
375 	return (0);
376 }
377 
378 /*
379  * Scale is a fixed-point number with the binary point 16 bits
380  * into the value, and is <= 1.0.  pc is at most 32 bits, so the
381  * intermediate result is at most 48 bits.
382  */
383 #define	PC_TO_INDEX(pc, prof) \
384 	((int)(((u_quad_t)((pc) - (prof)->pr_off) * \
385 	    (u_quad_t)((prof)->pr_scale)) >> 16) & ~1)
386 
387 /*
388  * Collect user-level profiling statistics; called on a profiling tick,
389  * when a process is running in user-mode.  This routine may be called
390  * from an interrupt context.  We try to update the user profiling buffers
391  * cheaply with fuswintr() and suswintr().  If that fails, we revert to
392  * an AST that will vector us to trap() with a context in which copyin
393  * and copyout will work.  Trap will then call addupc_task().
394  *
395  * Note that we may (rarely) not get around to the AST soon enough, and
396  * lose profile ticks when the next tick overwrites this one, but in this
397  * case the system is overloaded and the profile is probably already
398  * inaccurate.
399  */
400 void
401 addupc_intr(p, pc, ticks)
402 	register struct proc *p;
403 	register u_long pc;
404 	u_int ticks;
405 {
406 	register struct uprof *prof;
407 	register caddr_t addr;
408 	register u_int i;
409 	register int v;
410 
411 	if (ticks == 0)
412 		return;
413 	prof = &p->p_stats->p_prof;
414 	if (pc < prof->pr_off ||
415 	    (i = PC_TO_INDEX(pc, prof)) >= prof->pr_size)
416 		return;			/* out of range; ignore */
417 
418 	addr = prof->pr_base + i;
419 	if ((v = fuswintr(addr)) == -1 || suswintr(addr, v + ticks) == -1) {
420 		prof->pr_addr = pc;
421 		prof->pr_ticks = ticks;
422 		need_proftick(p);
423 	}
424 }
425 
426 /*
427  * Much like before, but we can afford to take faults here.  If the
428  * update fails, we simply turn off profiling.
429  */
430 void
431 addupc_task(p, pc, ticks)
432 	register struct proc *p;
433 	register u_long pc;
434 	u_int ticks;
435 {
436 	register struct uprof *prof;
437 	register caddr_t addr;
438 	register u_int i;
439 	u_short v;
440 
441 	/* Testing P_PROFIL may be unnecessary, but is certainly safe. */
442 	if ((p->p_flag & P_PROFIL) == 0 || ticks == 0)
443 		return;
444 
445 	prof = &p->p_stats->p_prof;
446 	if (pc < prof->pr_off ||
447 	    (i = PC_TO_INDEX(pc, prof)) >= prof->pr_size)
448 		return;
449 
450 	addr = prof->pr_base + i;
451 	if (copyin(addr, (caddr_t)&v, sizeof(v)) == 0) {
452 		v += ticks;
453 		if (copyout((caddr_t)&v, addr, sizeof(v)) == 0)
454 			return;
455 	}
456 	stopprofclock(p);
457 }
458