xref: /freebsd/sys/kern/subr_prof.c (revision 396c556d77189a5c474d35cec6f44a762e310b7d)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *	@(#)subr_prof.c	8.3 (Berkeley) 9/23/93
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
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 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 [%jx..%jx]\n",
166 	    p->textsize, (uintmax_t)p->lowpc, (uintmax_t)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 	p->histcounter_type = FUNCTION_ALIGNMENT / HISTFRACTION * NBBY;
184 
185 #ifdef GUPROF
186 	/* Signed counters. */
187 	p->histcounter_type = -p->histcounter_type;
188 
189 	/* Initialize pointers to overhead counters. */
190 	p->cputime_count = &KCOUNT(p, PC_TO_I(p, cputime));
191 	p->mcount_count = &KCOUNT(p, PC_TO_I(p, mcount));
192 	p->mexitcount_count = &KCOUNT(p, PC_TO_I(p, mexitcount));
193 
194 	/*
195 	 * Disable interrupts to avoid interference while we calibrate
196 	 * things.
197 	 */
198 	critical_enter();
199 
200 	/*
201 	 * Determine overheads.
202 	 * XXX this needs to be repeated for each useful timer/counter.
203 	 */
204 	cputime_overhead = 0;
205 	startguprof(p);
206 	for (i = 0; i < CALIB_SCALE; i++)
207 		cputime_overhead += cputime();
208 
209 	empty_loop();
210 	startguprof(p);
211 	empty_loop();
212 	empty_loop_time = cputime();
213 
214 	nullfunc_loop_profiled();
215 
216 	/*
217 	 * Start profiling.  There won't be any normal function calls since
218 	 * interrupts are disabled, but we will call the profiling routines
219 	 * directly to determine their overheads.
220 	 */
221 	p->state = GMON_PROF_HIRES;
222 
223 	startguprof(p);
224 	nullfunc_loop_profiled();
225 
226 	startguprof(p);
227 	for (i = 0; i < CALIB_SCALE; i++)
228 		MCOUNT_OVERHEAD(sys_profil);
229 	mcount_overhead = KCOUNT(p, PC_TO_I(p, sys_profil));
230 
231 	startguprof(p);
232 	for (i = 0; i < CALIB_SCALE; i++)
233 		MEXITCOUNT_OVERHEAD();
234 	MEXITCOUNT_OVERHEAD_GETLABEL(tmp_addr);
235 	mexitcount_overhead = KCOUNT(p, PC_TO_I(p, tmp_addr));
236 
237 	p->state = GMON_PROF_OFF;
238 	stopguprof(p);
239 
240 	critical_exit();
241 
242 	nullfunc_loop_profiled_time = 0;
243 	for (tmp_addr = (uintfptr_t)nullfunc_loop_profiled;
244 	     tmp_addr < (uintfptr_t)nullfunc_loop_profiled_end;
245 	     tmp_addr += HISTFRACTION * sizeof(HISTCOUNTER))
246 		nullfunc_loop_profiled_time += KCOUNT(p, PC_TO_I(p, tmp_addr));
247 #define CALIB_DOSCALE(count)	(((count) + CALIB_SCALE / 3) / CALIB_SCALE)
248 #define	c2n(count, freq)	((int)((count) * 1000000000LL / freq))
249 	printf("cputime %d, empty_loop %d, nullfunc_loop_profiled %d, mcount %d, mexitcount %d\n",
250 	       CALIB_DOSCALE(c2n(cputime_overhead, p->profrate)),
251 	       CALIB_DOSCALE(c2n(empty_loop_time, p->profrate)),
252 	       CALIB_DOSCALE(c2n(nullfunc_loop_profiled_time, p->profrate)),
253 	       CALIB_DOSCALE(c2n(mcount_overhead, p->profrate)),
254 	       CALIB_DOSCALE(c2n(mexitcount_overhead, p->profrate)));
255 	cputime_overhead -= empty_loop_time;
256 	mcount_overhead -= empty_loop_time;
257 	mexitcount_overhead -= empty_loop_time;
258 
259 	/*-
260 	 * Profiling overheads are determined by the times between the
261 	 * following events:
262 	 *	MC1: mcount() is called
263 	 *	MC2: cputime() (called from mcount()) latches the timer
264 	 *	MC3: mcount() completes
265 	 *	ME1: mexitcount() is called
266 	 *	ME2: cputime() (called from mexitcount()) latches the timer
267 	 *	ME3: mexitcount() completes.
268 	 * The times between the events vary slightly depending on instruction
269 	 * combination and cache misses, etc.  Attempt to determine the
270 	 * minimum times.  These can be subtracted from the profiling times
271 	 * without much risk of reducing the profiling times below what they
272 	 * would be when profiling is not configured.  Abbreviate:
273 	 *	ab = minimum time between MC1 and MC3
274 	 *	a  = minimum time between MC1 and MC2
275 	 *	b  = minimum time between MC2 and MC3
276 	 *	cd = minimum time between ME1 and ME3
277 	 *	c  = minimum time between ME1 and ME2
278 	 *	d  = minimum time between ME2 and ME3.
279 	 * These satisfy the relations:
280 	 *	ab            <= mcount_overhead		(just measured)
281 	 *	a + b         <= ab
282 	 *	        cd    <= mexitcount_overhead		(just measured)
283 	 *	        c + d <= cd
284 	 *	a         + d <= nullfunc_loop_profiled_time	(just measured)
285 	 *	a >= 0, b >= 0, c >= 0, d >= 0.
286 	 * Assume that ab and cd are equal to the minimums.
287 	 */
288 	p->cputime_overhead = CALIB_DOSCALE(cputime_overhead);
289 	p->mcount_overhead = CALIB_DOSCALE(mcount_overhead - cputime_overhead);
290 	p->mexitcount_overhead = CALIB_DOSCALE(mexitcount_overhead
291 					       - cputime_overhead);
292 	nullfunc_loop_overhead = nullfunc_loop_profiled_time - empty_loop_time;
293 	p->mexitcount_post_overhead = CALIB_DOSCALE((mcount_overhead
294 						     - nullfunc_loop_overhead)
295 						    / 4);
296 	p->mexitcount_pre_overhead = p->mexitcount_overhead
297 				     + p->cputime_overhead
298 				     - p->mexitcount_post_overhead;
299 	p->mcount_pre_overhead = CALIB_DOSCALE(nullfunc_loop_overhead)
300 				 - p->mexitcount_post_overhead;
301 	p->mcount_post_overhead = p->mcount_overhead
302 				  + p->cputime_overhead
303 				  - p->mcount_pre_overhead;
304 	printf(
305 "Profiling overheads: mcount: %d+%d, %d+%d; mexitcount: %d+%d, %d+%d nsec\n",
306 	       c2n(p->cputime_overhead, p->profrate),
307 	       c2n(p->mcount_overhead, p->profrate),
308 	       c2n(p->mcount_pre_overhead, p->profrate),
309 	       c2n(p->mcount_post_overhead, p->profrate),
310 	       c2n(p->cputime_overhead, p->profrate),
311 	       c2n(p->mexitcount_overhead, p->profrate),
312 	       c2n(p->mexitcount_pre_overhead, p->profrate),
313 	       c2n(p->mexitcount_post_overhead, p->profrate));
314 	printf(
315 "Profiling overheads: mcount: %d+%d, %d+%d; mexitcount: %d+%d, %d+%d cycles\n",
316 	       p->cputime_overhead, p->mcount_overhead,
317 	       p->mcount_pre_overhead, p->mcount_post_overhead,
318 	       p->cputime_overhead, p->mexitcount_overhead,
319 	       p->mexitcount_pre_overhead, p->mexitcount_post_overhead);
320 #endif /* GUPROF */
321 }
322 
323 /*
324  * Return kernel profiling information.
325  */
326 static int
327 sysctl_kern_prof(SYSCTL_HANDLER_ARGS)
328 {
329 	int *name = (int *) arg1;
330 	u_int namelen = arg2;
331 	struct gmonparam *gp = &_gmonparam;
332 	int error;
333 	int state;
334 
335 	/* all sysctl names at this level are terminal */
336 	if (namelen != 1)
337 		return (ENOTDIR);		/* overloaded */
338 
339 	switch (name[0]) {
340 	case GPROF_STATE:
341 		state = gp->state;
342 		error = sysctl_handle_int(oidp, &state, 0, req);
343 		if (error)
344 			return (error);
345 		if (!req->newptr)
346 			return (0);
347 		if (state == GMON_PROF_OFF) {
348 			gp->state = state;
349 			PROC_LOCK(&proc0);
350 			stopprofclock(&proc0);
351 			PROC_UNLOCK(&proc0);
352 			stopguprof(gp);
353 		} else if (state == GMON_PROF_ON) {
354 			gp->state = GMON_PROF_OFF;
355 			stopguprof(gp);
356 			gp->profrate = profhz;
357 			PROC_LOCK(&proc0);
358 			startprofclock(&proc0);
359 			PROC_UNLOCK(&proc0);
360 			gp->state = state;
361 #ifdef GUPROF
362 		} else if (state == GMON_PROF_HIRES) {
363 			gp->state = GMON_PROF_OFF;
364 			PROC_LOCK(&proc0);
365 			stopprofclock(&proc0);
366 			PROC_UNLOCK(&proc0);
367 			startguprof(gp);
368 			gp->state = state;
369 #endif
370 		} else if (state != gp->state)
371 			return (EINVAL);
372 		return (0);
373 	case GPROF_COUNT:
374 		return (sysctl_handle_opaque(oidp,
375 			gp->kcount, gp->kcountsize, req));
376 	case GPROF_FROMS:
377 		return (sysctl_handle_opaque(oidp,
378 			gp->froms, gp->fromssize, req));
379 	case GPROF_TOS:
380 		return (sysctl_handle_opaque(oidp,
381 			gp->tos, gp->tossize, req));
382 	case GPROF_GMONPARAM:
383 		return (sysctl_handle_opaque(oidp, gp, sizeof *gp, req));
384 	default:
385 		return (EOPNOTSUPP);
386 	}
387 	/* NOTREACHED */
388 }
389 
390 static SYSCTL_NODE(_kern, KERN_PROF, prof, CTLFLAG_RW, sysctl_kern_prof, "");
391 #endif /* GPROF */
392 
393 /*
394  * Profiling system call.
395  *
396  * The scale factor is a fixed point number with 16 bits of fraction, so that
397  * 1.0 is represented as 0x10000.  A scale factor of 0 turns off profiling.
398  */
399 #ifndef _SYS_SYSPROTO_H_
400 struct profil_args {
401 	caddr_t	samples;
402 	size_t	size;
403 	size_t	offset;
404 	u_int	scale;
405 };
406 #endif
407 /* ARGSUSED */
408 int
409 sys_profil(struct thread *td, struct profil_args *uap)
410 {
411 	struct uprof *upp;
412 	struct proc *p;
413 
414 	if (uap->scale > (1 << 16))
415 		return (EINVAL);
416 
417 	p = td->td_proc;
418 	if (uap->scale == 0) {
419 		PROC_LOCK(p);
420 		stopprofclock(p);
421 		PROC_UNLOCK(p);
422 		return (0);
423 	}
424 	PROC_LOCK(p);
425 	upp = &td->td_proc->p_stats->p_prof;
426 	PROC_PROFLOCK(p);
427 	upp->pr_off = uap->offset;
428 	upp->pr_scale = uap->scale;
429 	upp->pr_base = uap->samples;
430 	upp->pr_size = uap->size;
431 	PROC_PROFUNLOCK(p);
432 	startprofclock(p);
433 	PROC_UNLOCK(p);
434 
435 	return (0);
436 }
437 
438 /*
439  * Scale is a fixed-point number with the binary point 16 bits
440  * into the value, and is <= 1.0.  pc is at most 32 bits, so the
441  * intermediate result is at most 48 bits.
442  */
443 #define	PC_TO_INDEX(pc, prof) \
444 	((int)(((u_quad_t)((pc) - (prof)->pr_off) * \
445 	    (u_quad_t)((prof)->pr_scale)) >> 16) & ~1)
446 
447 /*
448  * Collect user-level profiling statistics; called on a profiling tick,
449  * when a process is running in user-mode.  This routine may be called
450  * from an interrupt context.  We try to update the user profiling buffers
451  * cheaply with fuswintr() and suswintr().  If that fails, we revert to
452  * an AST that will vector us to trap() with a context in which copyin
453  * and copyout will work.  Trap will then call addupc_task().
454  *
455  * Note that we may (rarely) not get around to the AST soon enough, and
456  * lose profile ticks when the next tick overwrites this one, but in this
457  * case the system is overloaded and the profile is probably already
458  * inaccurate.
459  */
460 void
461 addupc_intr(struct thread *td, uintfptr_t pc, u_int ticks)
462 {
463 	struct uprof *prof;
464 	caddr_t addr;
465 	u_int i;
466 	int v;
467 
468 	if (ticks == 0)
469 		return;
470 	prof = &td->td_proc->p_stats->p_prof;
471 	PROC_PROFLOCK(td->td_proc);
472 	if (pc < prof->pr_off ||
473 	    (i = PC_TO_INDEX(pc, prof)) >= prof->pr_size) {
474 		PROC_PROFUNLOCK(td->td_proc);
475 		return;			/* out of range; ignore */
476 	}
477 
478 	addr = prof->pr_base + i;
479 	PROC_PROFUNLOCK(td->td_proc);
480 	if ((v = fuswintr(addr)) == -1 || suswintr(addr, v + ticks) == -1) {
481 		td->td_profil_addr = pc;
482 		td->td_profil_ticks = ticks;
483 		td->td_pflags |= TDP_OWEUPC;
484 		thread_lock(td);
485 		td->td_flags |= TDF_ASTPENDING;
486 		thread_unlock(td);
487 	}
488 }
489 
490 /*
491  * Much like before, but we can afford to take faults here.  If the
492  * update fails, we simply turn off profiling.
493  */
494 void
495 addupc_task(struct thread *td, uintfptr_t pc, u_int ticks)
496 {
497 	struct proc *p = td->td_proc;
498 	struct uprof *prof;
499 	caddr_t addr;
500 	u_int i;
501 	u_short v;
502 	int stop = 0;
503 
504 	if (ticks == 0)
505 		return;
506 
507 	PROC_LOCK(p);
508 	if (!(p->p_flag & P_PROFIL)) {
509 		PROC_UNLOCK(p);
510 		return;
511 	}
512 	p->p_profthreads++;
513 	prof = &p->p_stats->p_prof;
514 	PROC_PROFLOCK(p);
515 	if (pc < prof->pr_off ||
516 	    (i = PC_TO_INDEX(pc, prof)) >= prof->pr_size) {
517 		PROC_PROFUNLOCK(p);
518 		goto out;
519 	}
520 
521 	addr = prof->pr_base + i;
522 	PROC_PROFUNLOCK(p);
523 	PROC_UNLOCK(p);
524 	if (copyin(addr, &v, sizeof(v)) == 0) {
525 		v += ticks;
526 		if (copyout(&v, addr, sizeof(v)) == 0) {
527 			PROC_LOCK(p);
528 			goto out;
529 		}
530 	}
531 	stop = 1;
532 	PROC_LOCK(p);
533 
534 out:
535 	if (--p->p_profthreads == 0) {
536 		if (p->p_flag & P_STOPPROF) {
537 			wakeup(&p->p_profthreads);
538 			p->p_flag &= ~P_STOPPROF;
539 			stop = 0;
540 		}
541 	}
542 	if (stop)
543 		stopprofclock(p);
544 	PROC_UNLOCK(p);
545 }
546