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