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