subr_prof.c revision 113874
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: head/sys/kern/subr_prof.c 113874 2003-04-22 20:54:04Z jhb $
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
54static MALLOC_DEFINE(M_GPROF, "gprof", "kernel profiling buffer");
55
56static void kmstartup(void *);
57SYSINIT(kmem, SI_SUB_KPROF, SI_ORDER_FIRST, kmstartup, NULL)
58
59struct gmonparam _gmonparam = { GMON_PROF_OFF };
60
61#ifdef GUPROF
62#include <machine/asmacros.h>
63
64void
65nullfunc_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
75void
76nullfunc_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 */
87void
88kmupetext(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
143static void
144kmstartup(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 */
338static int
339sysctl_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			PROC_LOCK(&proc0);
362			stopprofclock(&proc0);
363			PROC_UNLOCK(&proc0);
364			stopguprof(gp);
365		} else if (state == GMON_PROF_ON) {
366			gp->state = GMON_PROF_OFF;
367			stopguprof(gp);
368			gp->profrate = profhz;
369			PROC_LOCK(&proc0);
370			startprofclock(&proc0);
371			PROC_UNLOCK(&proc0);
372			gp->state = state;
373#ifdef GUPROF
374		} else if (state == GMON_PROF_HIRES) {
375			gp->state = GMON_PROF_OFF;
376			PROC_LOCK(&proc0);
377			stopprofclock(&proc0);
378			PROC_UNLOCK(&proc0);
379			startguprof(gp);
380			gp->state = state;
381#endif
382		} else if (state != gp->state)
383			return (EINVAL);
384		return (0);
385	case GPROF_COUNT:
386		return (sysctl_handle_opaque(oidp,
387			gp->kcount, gp->kcountsize, req));
388	case GPROF_FROMS:
389		return (sysctl_handle_opaque(oidp,
390			gp->froms, gp->fromssize, req));
391	case GPROF_TOS:
392		return (sysctl_handle_opaque(oidp,
393			gp->tos, gp->tossize, req));
394	case GPROF_GMONPARAM:
395		return (sysctl_handle_opaque(oidp, gp, sizeof *gp, req));
396	default:
397		return (EOPNOTSUPP);
398	}
399	/* NOTREACHED */
400}
401
402SYSCTL_NODE(_kern, KERN_PROF, prof, CTLFLAG_RW, sysctl_kern_prof, "");
403#endif /* GPROF */
404
405/*
406 * Profiling system call.
407 *
408 * The scale factor is a fixed point number with 16 bits of fraction, so that
409 * 1.0 is represented as 0x10000.  A scale factor of 0 turns off profiling.
410 */
411#ifndef _SYS_SYSPROTO_H_
412struct profil_args {
413	caddr_t	samples;
414	size_t	size;
415	size_t	offset;
416	u_int	scale;
417};
418#endif
419/*
420 * MPSAFE
421 */
422/* ARGSUSED */
423int
424profil(td, uap)
425	struct thread *td;
426	register struct profil_args *uap;
427{
428	struct uprof *upp;
429	struct proc *p;
430
431	if (uap->scale > (1 << 16))
432		return (EINVAL);
433
434	p = td->td_proc;
435	if (uap->scale == 0) {
436		PROC_LOCK(td->td_proc);
437		stopprofclock(td->td_proc);
438		PROC_UNLOCK(td->td_proc);
439		return (0);
440	}
441	upp = &td->td_proc->p_stats->p_prof;
442	upp->pr_off = uap->offset;
443	upp->pr_scale = uap->scale;
444	upp->pr_base = uap->samples;
445	upp->pr_size = uap->size;
446	PROC_LOCK(p);
447	startprofclock(p);
448	PROC_UNLOCK(p);
449
450	return (0);
451}
452
453/*
454 * Scale is a fixed-point number with the binary point 16 bits
455 * into the value, and is <= 1.0.  pc is at most 32 bits, so the
456 * intermediate result is at most 48 bits.
457 */
458#define	PC_TO_INDEX(pc, prof) \
459	((int)(((u_quad_t)((pc) - (prof)->pr_off) * \
460	    (u_quad_t)((prof)->pr_scale)) >> 16) & ~1)
461
462/*
463 * Collect user-level profiling statistics; called on a profiling tick,
464 * when a process is running in user-mode.  This routine may be called
465 * from an interrupt context.  We try to update the user profiling buffers
466 * cheaply with fuswintr() and suswintr().  If that fails, we revert to
467 * an AST that will vector us to trap() with a context in which copyin
468 * and copyout will work.  Trap will then call addupc_task().
469 *
470 * Note that we may (rarely) not get around to the AST soon enough, and
471 * lose profile ticks when the next tick overwrites this one, but in this
472 * case the system is overloaded and the profile is probably already
473 * inaccurate.
474 */
475void
476addupc_intr(struct thread *td, uintptr_t pc, u_int ticks)
477{
478	struct uprof *prof;
479	caddr_t addr;
480	u_int i;
481	int v;
482
483	if (ticks == 0)
484		return;
485	prof = &td->td_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		td->td_flags |= TDF_OWEUPC | TDF_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 * XXXKSE, don't use kse unless we got sched lock.
504 */
505void
506addupc_task(struct thread *td, uintptr_t pc, u_int ticks)
507{
508	struct proc *p = td->td_proc;
509	struct uprof *prof;
510	caddr_t addr;
511	u_int i;
512	u_short v;
513	int stop = 0;
514
515	if (ticks == 0)
516		return;
517
518	PROC_LOCK(p);
519	if (!(p->p_flag & P_PROFIL)) {
520		PROC_UNLOCK(p);
521		return;
522	}
523	p->p_profthreads++;
524	PROC_UNLOCK(p);
525	prof = &p->p_stats->p_prof;
526	if (pc < prof->pr_off ||
527	    (i = PC_TO_INDEX(pc, prof)) >= prof->pr_size) {
528		goto out;
529	}
530
531	addr = prof->pr_base + i;
532	if (copyin(addr, &v, sizeof(v)) == 0) {
533		v += ticks;
534		if (copyout(&v, addr, sizeof(v)) == 0)
535			goto out;
536	}
537	stop = 1;
538
539out:
540	PROC_LOCK(p);
541	if (--p->p_profthreads == 0) {
542		if (p->p_flag & P_STOPPROF) {
543			wakeup(&p->p_profthreads);
544			stop = 0;
545		}
546	}
547	if (stop)
548		stopprofclock(p);
549	PROC_UNLOCK(p);
550}
551
552#if defined(__i386__) && __GNUC__ >= 2
553/*
554 * Support for "--test-coverage --profile-arcs" in GCC.
555 *
556 * We need to call all the functions in the .ctor section, in order
557 * to get all the counter-arrays strung into a list.
558 *
559 * XXX: the .ctors call __bb_init_func which is located in over in
560 * XXX: i386/i386/support.s for historical reasons.  There is probably
561 * XXX: no reason for that to be assembler anymore, but doing it right
562 * XXX: in MI C code requires one to reverse-engineer the type-selection
563 * XXX: inside GCC.  Have fun.
564 *
565 * XXX: Worrisome perspective: Calling the .ctors may make C++ in the
566 * XXX: kernel feasible.  Don't.
567 */
568typedef void (*ctor_t)(void);
569extern ctor_t _start_ctors, _stop_ctors;
570
571static void
572tcov_init(void *foo __unused)
573{
574	ctor_t *p, q;
575
576	for (p = &_start_ctors; p < &_stop_ctors; p++) {
577		q = *p;
578		q();
579	}
580}
581
582SYSINIT(tcov_init, SI_SUB_KPROF, SI_ORDER_SECOND, tcov_init, NULL)
583
584/*
585 * GCC contains magic to recognize calls to for instance execve() and
586 * puts in calls to this function to preserve the profile counters.
587 * XXX: Put zinging punchline here.
588 */
589void __bb_fork_func(void);
590void
591__bb_fork_func(void)
592{
593}
594
595#endif
596
597