kgmon.c revision 91009
1/*
2 * Copyright (c) 1983, 1992, 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
34#ifndef lint
35static const char copyright[] =
36"@(#) Copyright (c) 1983, 1992, 1993\n\
37	The Regents of the University of California.  All rights reserved.\n";
38#endif /* not lint */
39
40#ifndef lint
41#if 0
42static char sccsid[] = "@(#)kgmon.c	8.1 (Berkeley) 6/6/93";
43#endif
44static const char rcsid[] =
45  "$FreeBSD: head/usr.sbin/kgmon/kgmon.c 91009 2002-02-21 05:52:49Z bde $";
46#endif /* not lint */
47
48#include <sys/param.h>
49#include <sys/file.h>
50#include <sys/time.h>
51#include <sys/sysctl.h>
52#include <sys/gmon.h>
53#include <ctype.h>
54#include <err.h>
55#include <errno.h>
56#include <kvm.h>
57#include <limits.h>
58#include <nlist.h>
59#include <paths.h>
60#include <stddef.h>
61#include <stdio.h>
62#include <stdlib.h>
63#include <string.h>
64#include <unistd.h>
65
66struct nlist nl[] = {
67#define	N_GMONPARAM	0
68	{ "__gmonparam" },
69#define	N_PROFHZ	1
70	{ "_profhz" },
71	{ NULL },
72};
73
74struct kvmvars {
75	kvm_t	*kd;
76	struct gmonparam gpm;
77};
78
79int	Bflag, bflag, hflag, kflag, rflag, pflag;
80int	debug = 0;
81int	getprof __P((struct kvmvars *));
82int	getprofhz __P((struct kvmvars *));
83void	kern_readonly __P((int));
84int	openfiles __P((char *, char *, struct kvmvars *));
85void	setprof __P((struct kvmvars *kvp, int state));
86void	dumpstate __P((struct kvmvars *kvp));
87void	reset __P((struct kvmvars *kvp));
88static void usage __P((void));
89
90int
91main(int argc, char **argv)
92{
93	int ch, mode, disp, accessmode;
94	struct kvmvars kvmvars;
95	char *system, *kmemf;
96
97	seteuid(getuid());
98	kmemf = NULL;
99	system = NULL;
100	while ((ch = getopt(argc, argv, "M:N:Bbhpr")) != -1) {
101		switch((char)ch) {
102
103		case 'M':
104			kmemf = optarg;
105			kflag = 1;
106			break;
107
108		case 'N':
109			system = optarg;
110			break;
111
112		case 'B':
113			Bflag = 1;
114			break;
115
116		case 'b':
117			bflag = 1;
118			break;
119
120		case 'h':
121			hflag = 1;
122			break;
123
124		case 'p':
125			pflag = 1;
126			break;
127
128		case 'r':
129			rflag = 1;
130			break;
131
132		default:
133			usage();
134		}
135	}
136	argc -= optind;
137	argv += optind;
138
139#define BACKWARD_COMPATIBILITY
140#ifdef	BACKWARD_COMPATIBILITY
141	if (*argv) {
142		system = *argv;
143		if (*++argv) {
144			kmemf = *argv;
145			++kflag;
146		}
147	}
148#endif
149	if (system == NULL)
150		system = (char *)getbootfile();
151	accessmode = openfiles(system, kmemf, &kvmvars);
152	mode = getprof(&kvmvars);
153	if (hflag)
154		disp = GMON_PROF_OFF;
155	else if (Bflag)
156		disp = GMON_PROF_HIRES;
157	else if (bflag)
158		disp = GMON_PROF_ON;
159	else
160		disp = mode;
161	if (pflag)
162		dumpstate(&kvmvars);
163	if (rflag)
164		reset(&kvmvars);
165	if (accessmode == O_RDWR)
166		setprof(&kvmvars, disp);
167	(void)fprintf(stdout, "kgmon: kernel profiling is %s.\n",
168		      disp == GMON_PROF_OFF ? "off" :
169		      disp == GMON_PROF_HIRES ? "running (high resolution)" :
170		      disp == GMON_PROF_ON ? "running" :
171		      disp == GMON_PROF_BUSY ? "busy" :
172		      disp == GMON_PROF_ERROR ? "off (error)" :
173		      "in an unknown state");
174	return (0);
175}
176
177static void
178usage()
179{
180	fprintf(stderr, "usage: kgmon [-Bbhrp] [-M core] [-N system]\n");
181	exit(1);
182}
183
184/*
185 * Check that profiling is enabled and open any ncessary files.
186 */
187int
188openfiles(system, kmemf, kvp)
189	char *system;
190	char *kmemf;
191	struct kvmvars *kvp;
192{
193	int mib[3], state, size, openmode;
194	char errbuf[_POSIX2_LINE_MAX];
195
196	if (!kflag) {
197		mib[0] = CTL_KERN;
198		mib[1] = KERN_PROF;
199		mib[2] = GPROF_STATE;
200		size = sizeof state;
201		if (sysctl(mib, 3, &state, &size, NULL, 0) < 0)
202			errx(20, "profiling not defined in kernel");
203		if (!(Bflag || bflag || hflag || rflag ||
204		    (pflag &&
205		     (state == GMON_PROF_HIRES || state == GMON_PROF_ON))))
206			return (O_RDONLY);
207		(void)seteuid(0);
208		if (sysctl(mib, 3, NULL, NULL, &state, size) >= 0)
209			return (O_RDWR);
210		(void)seteuid(getuid());
211		kern_readonly(state);
212		return (O_RDONLY);
213	}
214	openmode = (Bflag || bflag || hflag || pflag || rflag)
215		   ? O_RDWR : O_RDONLY;
216	kvp->kd = kvm_openfiles(system, kmemf, NULL, openmode, errbuf);
217	if (kvp->kd == NULL) {
218		if (openmode == O_RDWR) {
219			openmode = O_RDONLY;
220			kvp->kd = kvm_openfiles(system, kmemf, NULL, O_RDONLY,
221			    errbuf);
222		}
223		if (kvp->kd == NULL)
224			errx(2, "kvm_openfiles: %s", errbuf);
225		kern_readonly(GMON_PROF_ON);
226	}
227	if (kvm_nlist(kvp->kd, nl) < 0)
228		errx(3, "%s: no namelist", system);
229	if (!nl[N_GMONPARAM].n_value)
230		errx(20, "profiling not defined in kernel");
231	return (openmode);
232}
233
234/*
235 * Suppress options that require a writable kernel.
236 */
237void
238kern_readonly(mode)
239	int mode;
240{
241
242	(void)fprintf(stderr, "kgmon: kernel read-only: ");
243	if (pflag && (mode == GMON_PROF_HIRES || mode == GMON_PROF_ON))
244		(void)fprintf(stderr, "data may be inconsistent\n");
245	if (rflag)
246		(void)fprintf(stderr, "-r supressed\n");
247	if (Bflag)
248		(void)fprintf(stderr, "-B supressed\n");
249	if (bflag)
250		(void)fprintf(stderr, "-b supressed\n");
251	if (hflag)
252		(void)fprintf(stderr, "-h supressed\n");
253	rflag = Bflag = bflag = hflag = 0;
254}
255
256/*
257 * Get the state of kernel profiling.
258 */
259int
260getprof(kvp)
261	struct kvmvars *kvp;
262{
263	int mib[3], size;
264
265	if (kflag) {
266		size = kvm_read(kvp->kd, nl[N_GMONPARAM].n_value, &kvp->gpm,
267		    sizeof kvp->gpm);
268	} else {
269		mib[0] = CTL_KERN;
270		mib[1] = KERN_PROF;
271		mib[2] = GPROF_GMONPARAM;
272		size = sizeof kvp->gpm;
273		if (sysctl(mib, 3, &kvp->gpm, &size, NULL, 0) < 0)
274			size = 0;
275	}
276
277	/*
278	 * Accept certain undersized "structs" from old kernels.  We need
279	 * everything up to hashfraction, and want profrate and
280	 * histcounter_type.  Assume that the kernel doesn't put garbage
281	 * in any padding that is returned instead of profrate and
282	 * histcounter_type.  This is a bad assumption for dead kernels,
283	 * since kvm_read() will normally return garbage for bytes beyond
284	 * the end of the actual kernel struct, if any.
285	 */
286	if (size < offsetof(struct gmonparam, hashfraction) +
287	    sizeof(kvp->gpm.hashfraction) || size > sizeof(kvp->gpm))
288		errx(4, "cannot get gmonparam: %s",
289		    kflag ? kvm_geterr(kvp->kd) : strerror(errno));
290	bzero((char *)&kvp->gpm + size, sizeof(kvp->gpm) - size);
291	if (kvp->gpm.profrate == 0)
292		kvp->gpm.profrate = getprofhz(kvp);
293#ifdef __i386__
294	if (kvp->gpm.histcounter_type == 0) {
295		/*
296		 * This fixup only works for not-so-old i386 kernels.  The
297		 * magic 16 is the kernel FUNCTION_ALIGNMENT.  64-bit
298		 * counters are signed; smaller counters are unsigned.
299		 */
300		kvp->gpm.histcounter_type = 16 /
301		    (kvp->gpm.textsize / kvp->gpm.kcountsize) * CHAR_BIT;
302		if (kvp->gpm.histcounter_type == 64)
303			kvp->gpm.histcounter_type = -64;
304	}
305#endif
306
307	return (kvp->gpm.state);
308}
309
310/*
311 * Enable or disable kernel profiling according to the state variable.
312 */
313void
314setprof(kvp, state)
315	struct kvmvars *kvp;
316	int state;
317{
318	struct gmonparam *p = (struct gmonparam *)nl[N_GMONPARAM].n_value;
319	int mib[3], sz, oldstate;
320
321	sz = sizeof(state);
322	if (!kflag) {
323		mib[0] = CTL_KERN;
324		mib[1] = KERN_PROF;
325		mib[2] = GPROF_STATE;
326		if (sysctl(mib, 3, &oldstate, &sz, NULL, 0) < 0)
327			goto bad;
328		if (oldstate == state)
329			return;
330		(void)seteuid(0);
331		if (sysctl(mib, 3, NULL, NULL, &state, sz) >= 0) {
332			(void)seteuid(getuid());
333			return;
334		}
335		(void)seteuid(getuid());
336	} else if (kvm_write(kvp->kd, (u_long)&p->state, (void *)&state, sz)
337	    == sz)
338		return;
339bad:
340	warnx("warning: cannot turn profiling %s",
341	    state == GMON_PROF_OFF ? "off" : "on");
342}
343
344/*
345 * Build the gmon.out file.
346 */
347void
348dumpstate(kvp)
349	struct kvmvars *kvp;
350{
351	register FILE *fp;
352	struct rawarc rawarc;
353	struct tostruct *tos;
354	u_long frompc;
355	u_short *froms, *tickbuf;
356	int mib[3], i;
357	struct gmonhdr h;
358	int fromindex, endfrom, toindex;
359
360	setprof(kvp, GMON_PROF_OFF);
361	fp = fopen("gmon.out", "w");
362	if (fp == 0) {
363		warn("gmon.out");
364		return;
365	}
366
367	/*
368	 * Build the gmon header and write it to a file.
369	 */
370	bzero(&h, sizeof(h));
371	h.lpc = kvp->gpm.lowpc;
372	h.hpc = kvp->gpm.highpc;
373	h.ncnt = kvp->gpm.kcountsize + sizeof(h);
374	h.version = GMONVERSION;
375	h.profrate = kvp->gpm.profrate;
376	h.histcounter_type = kvp->gpm.histcounter_type;
377	fwrite((char *)&h, sizeof(h), 1, fp);
378
379	/*
380	 * Write out the tick buffer.
381	 */
382	mib[0] = CTL_KERN;
383	mib[1] = KERN_PROF;
384	if ((tickbuf = (u_short *)malloc(kvp->gpm.kcountsize)) == NULL)
385		errx(5, "cannot allocate kcount space");
386	if (kflag) {
387		i = kvm_read(kvp->kd, (u_long)kvp->gpm.kcount, (void *)tickbuf,
388		    kvp->gpm.kcountsize);
389	} else {
390		mib[2] = GPROF_COUNT;
391		i = kvp->gpm.kcountsize;
392		if (sysctl(mib, 3, tickbuf, &i, NULL, 0) < 0)
393			i = 0;
394	}
395	if (i != kvp->gpm.kcountsize)
396		errx(6, "read ticks: read %u, got %d: %s",
397		    kvp->gpm.kcountsize, i,
398		    kflag ? kvm_geterr(kvp->kd) : strerror(errno));
399	if ((fwrite(tickbuf, kvp->gpm.kcountsize, 1, fp)) != 1)
400		err(7, "writing tocks to gmon.out");
401	free(tickbuf);
402
403	/*
404	 * Write out the arc info.
405	 */
406	if ((froms = (u_short *)malloc(kvp->gpm.fromssize)) == NULL)
407		errx(8, "cannot allocate froms space");
408	if (kflag) {
409		i = kvm_read(kvp->kd, (u_long)kvp->gpm.froms, (void *)froms,
410		    kvp->gpm.fromssize);
411	} else {
412		mib[2] = GPROF_FROMS;
413		i = kvp->gpm.fromssize;
414		if (sysctl(mib, 3, froms, &i, NULL, 0) < 0)
415			i = 0;
416	}
417	if (i != kvp->gpm.fromssize)
418		errx(9, "read froms: read %u, got %d: %s",
419		    kvp->gpm.fromssize, i,
420		    kflag ? kvm_geterr(kvp->kd) : strerror(errno));
421	if ((tos = (struct tostruct *)malloc(kvp->gpm.tossize)) == NULL)
422		errx(10, "cannot allocate tos space");
423	if (kflag) {
424		i = kvm_read(kvp->kd, (u_long)kvp->gpm.tos, (void *)tos,
425		    kvp->gpm.tossize);
426	} else {
427		mib[2] = GPROF_TOS;
428		i = kvp->gpm.tossize;
429		if (sysctl(mib, 3, tos, &i, NULL, 0) < 0)
430			i = 0;
431	}
432	if (i != kvp->gpm.tossize)
433		errx(11, "read tos: read %u, got %d: %s",
434		    kvp->gpm.tossize, i,
435		    kflag ? kvm_geterr(kvp->kd) : strerror(errno));
436	if (debug)
437		warnx("lowpc 0x%x, textsize 0x%x",
438			      kvp->gpm.lowpc, kvp->gpm.textsize);
439	endfrom = kvp->gpm.fromssize / sizeof(*froms);
440	for (fromindex = 0; fromindex < endfrom; ++fromindex) {
441		if (froms[fromindex] == 0)
442			continue;
443		frompc = (u_long)kvp->gpm.lowpc +
444		    (fromindex * kvp->gpm.hashfraction * sizeof(*froms));
445		for (toindex = froms[fromindex]; toindex != 0;
446		   toindex = tos[toindex].link) {
447			if (debug)
448			    warnx("[mcleanup] frompc 0x%x selfpc 0x%x count %d",
449			    frompc, tos[toindex].selfpc,
450			    tos[toindex].count);
451			rawarc.raw_frompc = frompc;
452			rawarc.raw_selfpc = (u_long)tos[toindex].selfpc;
453			rawarc.raw_count = tos[toindex].count;
454			fwrite((char *)&rawarc, sizeof(rawarc), 1, fp);
455		}
456	}
457	fclose(fp);
458}
459
460/*
461 * Get the profiling rate.
462 */
463int
464getprofhz(kvp)
465	struct kvmvars *kvp;
466{
467	int mib[2], size, profrate;
468	struct clockinfo clockrate;
469
470	if (kflag) {
471		profrate = 1;
472		if (kvm_read(kvp->kd, nl[N_PROFHZ].n_value, &profrate,
473		    sizeof profrate) != sizeof profrate)
474			warnx("get clockrate: %s", kvm_geterr(kvp->kd));
475		return (profrate);
476	}
477	mib[0] = CTL_KERN;
478	mib[1] = KERN_CLOCKRATE;
479	clockrate.profhz = 1;
480	size = sizeof clockrate;
481	if (sysctl(mib, 2, &clockrate, &size, NULL, 0) < 0)
482		warn("get clockrate");
483	return (clockrate.profhz);
484}
485
486/*
487 * Reset the kernel profiling date structures.
488 */
489void
490reset(kvp)
491	struct kvmvars *kvp;
492{
493	char *zbuf;
494	u_long biggest;
495	int mib[3];
496
497	setprof(kvp, GMON_PROF_OFF);
498
499	biggest = kvp->gpm.kcountsize;
500	if (kvp->gpm.fromssize > biggest)
501		biggest = kvp->gpm.fromssize;
502	if (kvp->gpm.tossize > biggest)
503		biggest = kvp->gpm.tossize;
504	if ((zbuf = (char *)malloc(biggest)) == NULL)
505		errx(12, "cannot allocate zbuf space");
506	bzero(zbuf, biggest);
507	if (kflag) {
508		if (kvm_write(kvp->kd, (u_long)kvp->gpm.kcount, zbuf,
509		    kvp->gpm.kcountsize) != kvp->gpm.kcountsize)
510			errx(13, "tickbuf zero: %s", kvm_geterr(kvp->kd));
511		if (kvm_write(kvp->kd, (u_long)kvp->gpm.froms, zbuf,
512		    kvp->gpm.fromssize) != kvp->gpm.fromssize)
513			errx(14, "froms zero: %s", kvm_geterr(kvp->kd));
514		if (kvm_write(kvp->kd, (u_long)kvp->gpm.tos, zbuf,
515		    kvp->gpm.tossize) != kvp->gpm.tossize)
516			errx(15, "tos zero: %s", kvm_geterr(kvp->kd));
517		return;
518	}
519	(void)seteuid(0);
520	mib[0] = CTL_KERN;
521	mib[1] = KERN_PROF;
522	mib[2] = GPROF_COUNT;
523	if (sysctl(mib, 3, NULL, NULL, zbuf, kvp->gpm.kcountsize) < 0)
524		err(13, "tickbuf zero");
525	mib[2] = GPROF_FROMS;
526	if (sysctl(mib, 3, NULL, NULL, zbuf, kvp->gpm.fromssize) < 0)
527		err(14, "froms zero");
528	mib[2] = GPROF_TOS;
529	if (sysctl(mib, 3, NULL, NULL, zbuf, kvp->gpm.tossize) < 0)
530		err(15, "tos zero");
531	(void)seteuid(getuid());
532	free(zbuf);
533}
534