kgmon.c revision 100904
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 100904 2002-07-30 04:45:14Z jake $";
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(struct kvmvars *);
82int	getprofhz(struct kvmvars *);
83void	kern_readonly(int);
84int	openfiles(char *, char *, struct kvmvars *);
85void	setprof(struct kvmvars *kvp, int state);
86void	dumpstate(struct kvmvars *kvp);
87void	reset(struct kvmvars *kvp);
88static void usage(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	size_t size;
194	int mib[3], state, openmode;
195	char errbuf[_POSIX2_LINE_MAX];
196
197	if (!kflag) {
198		mib[0] = CTL_KERN;
199		mib[1] = KERN_PROF;
200		mib[2] = GPROF_STATE;
201		size = sizeof state;
202		if (sysctl(mib, 3, &state, &size, NULL, 0) < 0)
203			errx(20, "profiling not defined in kernel");
204		if (!(Bflag || bflag || hflag || rflag ||
205		    (pflag &&
206		     (state == GMON_PROF_HIRES || state == GMON_PROF_ON))))
207			return (O_RDONLY);
208		(void)seteuid(0);
209		if (sysctl(mib, 3, NULL, NULL, &state, size) >= 0)
210			return (O_RDWR);
211		(void)seteuid(getuid());
212		kern_readonly(state);
213		return (O_RDONLY);
214	}
215	openmode = (Bflag || bflag || hflag || pflag || rflag)
216		   ? O_RDWR : O_RDONLY;
217	kvp->kd = kvm_openfiles(system, kmemf, NULL, openmode, errbuf);
218	if (kvp->kd == NULL) {
219		if (openmode == O_RDWR) {
220			openmode = O_RDONLY;
221			kvp->kd = kvm_openfiles(system, kmemf, NULL, O_RDONLY,
222			    errbuf);
223		}
224		if (kvp->kd == NULL)
225			errx(2, "kvm_openfiles: %s", errbuf);
226		kern_readonly(GMON_PROF_ON);
227	}
228	if (kvm_nlist(kvp->kd, nl) < 0)
229		errx(3, "%s: no namelist", system);
230	if (!nl[N_GMONPARAM].n_value)
231		errx(20, "profiling not defined in kernel");
232	return (openmode);
233}
234
235/*
236 * Suppress options that require a writable kernel.
237 */
238void
239kern_readonly(mode)
240	int mode;
241{
242
243	(void)fprintf(stderr, "kgmon: kernel read-only: ");
244	if (pflag && (mode == GMON_PROF_HIRES || mode == GMON_PROF_ON))
245		(void)fprintf(stderr, "data may be inconsistent\n");
246	if (rflag)
247		(void)fprintf(stderr, "-r supressed\n");
248	if (Bflag)
249		(void)fprintf(stderr, "-B supressed\n");
250	if (bflag)
251		(void)fprintf(stderr, "-b supressed\n");
252	if (hflag)
253		(void)fprintf(stderr, "-h supressed\n");
254	rflag = Bflag = bflag = hflag = 0;
255}
256
257/*
258 * Get the state of kernel profiling.
259 */
260int
261getprof(kvp)
262	struct kvmvars *kvp;
263{
264	size_t size;
265	int mib[3];
266
267	if (kflag) {
268		size = kvm_read(kvp->kd, nl[N_GMONPARAM].n_value, &kvp->gpm,
269		    sizeof kvp->gpm);
270	} else {
271		mib[0] = CTL_KERN;
272		mib[1] = KERN_PROF;
273		mib[2] = GPROF_GMONPARAM;
274		size = sizeof kvp->gpm;
275		if (sysctl(mib, 3, &kvp->gpm, &size, NULL, 0) < 0)
276			size = 0;
277	}
278
279	/*
280	 * Accept certain undersized "structs" from old kernels.  We need
281	 * everything up to hashfraction, and want profrate and
282	 * histcounter_type.  Assume that the kernel doesn't put garbage
283	 * in any padding that is returned instead of profrate and
284	 * histcounter_type.  This is a bad assumption for dead kernels,
285	 * since kvm_read() will normally return garbage for bytes beyond
286	 * the end of the actual kernel struct, if any.
287	 */
288	if (size < offsetof(struct gmonparam, hashfraction) +
289	    sizeof(kvp->gpm.hashfraction) || size > sizeof(kvp->gpm))
290		errx(4, "cannot get gmonparam: %s",
291		    kflag ? kvm_geterr(kvp->kd) : strerror(errno));
292	bzero((char *)&kvp->gpm + size, sizeof(kvp->gpm) - size);
293	if (kvp->gpm.profrate == 0)
294		kvp->gpm.profrate = getprofhz(kvp);
295#ifdef __i386__
296	if (kvp->gpm.histcounter_type == 0) {
297		/*
298		 * This fixup only works for not-so-old i386 kernels.  The
299		 * magic 16 is the kernel FUNCTION_ALIGNMENT.  64-bit
300		 * counters are signed; smaller counters are unsigned.
301		 */
302		kvp->gpm.histcounter_type = 16 /
303		    (kvp->gpm.textsize / kvp->gpm.kcountsize) * CHAR_BIT;
304		if (kvp->gpm.histcounter_type == 64)
305			kvp->gpm.histcounter_type = -64;
306	}
307#endif
308
309	return (kvp->gpm.state);
310}
311
312/*
313 * Enable or disable kernel profiling according to the state variable.
314 */
315void
316setprof(kvp, state)
317	struct kvmvars *kvp;
318	int state;
319{
320	struct gmonparam *p = (struct gmonparam *)nl[N_GMONPARAM].n_value;
321	size_t sz;
322	int mib[3], oldstate;
323
324	sz = sizeof(state);
325	if (!kflag) {
326		mib[0] = CTL_KERN;
327		mib[1] = KERN_PROF;
328		mib[2] = GPROF_STATE;
329		if (sysctl(mib, 3, &oldstate, &sz, NULL, 0) < 0)
330			goto bad;
331		if (oldstate == state)
332			return;
333		(void)seteuid(0);
334		if (sysctl(mib, 3, NULL, NULL, &state, sz) >= 0) {
335			(void)seteuid(getuid());
336			return;
337		}
338		(void)seteuid(getuid());
339	} else if (kvm_write(kvp->kd, (u_long)&p->state, (void *)&state, sz)
340	    == sz)
341		return;
342bad:
343	warnx("warning: cannot turn profiling %s",
344	    state == GMON_PROF_OFF ? "off" : "on");
345}
346
347/*
348 * Build the gmon.out file.
349 */
350void
351dumpstate(kvp)
352	struct kvmvars *kvp;
353{
354	register FILE *fp;
355	struct rawarc rawarc;
356	struct tostruct *tos;
357	u_long frompc;
358	u_short *froms, *tickbuf;
359	size_t i;
360	int mib[3];
361	struct gmonhdr h;
362	int fromindex, endfrom, toindex;
363
364	setprof(kvp, GMON_PROF_OFF);
365	fp = fopen("gmon.out", "w");
366	if (fp == 0) {
367		warn("gmon.out");
368		return;
369	}
370
371	/*
372	 * Build the gmon header and write it to a file.
373	 */
374	bzero(&h, sizeof(h));
375	h.lpc = kvp->gpm.lowpc;
376	h.hpc = kvp->gpm.highpc;
377	h.ncnt = kvp->gpm.kcountsize + sizeof(h);
378	h.version = GMONVERSION;
379	h.profrate = kvp->gpm.profrate;
380	h.histcounter_type = kvp->gpm.histcounter_type;
381	fwrite((char *)&h, sizeof(h), 1, fp);
382
383	/*
384	 * Write out the tick buffer.
385	 */
386	mib[0] = CTL_KERN;
387	mib[1] = KERN_PROF;
388	if ((tickbuf = (u_short *)malloc(kvp->gpm.kcountsize)) == NULL)
389		errx(5, "cannot allocate kcount space");
390	if (kflag) {
391		i = kvm_read(kvp->kd, (u_long)kvp->gpm.kcount, (void *)tickbuf,
392		    kvp->gpm.kcountsize);
393	} else {
394		mib[2] = GPROF_COUNT;
395		i = kvp->gpm.kcountsize;
396		if (sysctl(mib, 3, tickbuf, &i, NULL, 0) < 0)
397			i = 0;
398	}
399	if (i != kvp->gpm.kcountsize)
400		errx(6, "read ticks: read %u, got %d: %s",
401		    kvp->gpm.kcountsize, i,
402		    kflag ? kvm_geterr(kvp->kd) : strerror(errno));
403	if ((fwrite(tickbuf, kvp->gpm.kcountsize, 1, fp)) != 1)
404		err(7, "writing tocks to gmon.out");
405	free(tickbuf);
406
407	/*
408	 * Write out the arc info.
409	 */
410	if ((froms = (u_short *)malloc(kvp->gpm.fromssize)) == NULL)
411		errx(8, "cannot allocate froms space");
412	if (kflag) {
413		i = kvm_read(kvp->kd, (u_long)kvp->gpm.froms, (void *)froms,
414		    kvp->gpm.fromssize);
415	} else {
416		mib[2] = GPROF_FROMS;
417		i = kvp->gpm.fromssize;
418		if (sysctl(mib, 3, froms, &i, NULL, 0) < 0)
419			i = 0;
420	}
421	if (i != kvp->gpm.fromssize)
422		errx(9, "read froms: read %u, got %d: %s",
423		    kvp->gpm.fromssize, i,
424		    kflag ? kvm_geterr(kvp->kd) : strerror(errno));
425	if ((tos = (struct tostruct *)malloc(kvp->gpm.tossize)) == NULL)
426		errx(10, "cannot allocate tos space");
427	if (kflag) {
428		i = kvm_read(kvp->kd, (u_long)kvp->gpm.tos, (void *)tos,
429		    kvp->gpm.tossize);
430	} else {
431		mib[2] = GPROF_TOS;
432		i = kvp->gpm.tossize;
433		if (sysctl(mib, 3, tos, &i, NULL, 0) < 0)
434			i = 0;
435	}
436	if (i != kvp->gpm.tossize)
437		errx(11, "read tos: read %u, got %d: %s",
438		    kvp->gpm.tossize, i,
439		    kflag ? kvm_geterr(kvp->kd) : strerror(errno));
440	if (debug)
441		warnx("lowpc 0x%x, textsize 0x%x",
442			      kvp->gpm.lowpc, kvp->gpm.textsize);
443	endfrom = kvp->gpm.fromssize / sizeof(*froms);
444	for (fromindex = 0; fromindex < endfrom; ++fromindex) {
445		if (froms[fromindex] == 0)
446			continue;
447		frompc = (u_long)kvp->gpm.lowpc +
448		    (fromindex * kvp->gpm.hashfraction * sizeof(*froms));
449		for (toindex = froms[fromindex]; toindex != 0;
450		   toindex = tos[toindex].link) {
451			if (debug)
452			    warnx("[mcleanup] frompc 0x%x selfpc 0x%x count %d",
453			    frompc, tos[toindex].selfpc,
454			    tos[toindex].count);
455			rawarc.raw_frompc = frompc;
456			rawarc.raw_selfpc = (u_long)tos[toindex].selfpc;
457			rawarc.raw_count = tos[toindex].count;
458			fwrite((char *)&rawarc, sizeof(rawarc), 1, fp);
459		}
460	}
461	fclose(fp);
462}
463
464/*
465 * Get the profiling rate.
466 */
467int
468getprofhz(kvp)
469	struct kvmvars *kvp;
470{
471	size_t size;
472	int mib[2], profrate;
473	struct clockinfo clockrate;
474
475	if (kflag) {
476		profrate = 1;
477		if (kvm_read(kvp->kd, nl[N_PROFHZ].n_value, &profrate,
478		    sizeof profrate) != sizeof profrate)
479			warnx("get clockrate: %s", kvm_geterr(kvp->kd));
480		return (profrate);
481	}
482	mib[0] = CTL_KERN;
483	mib[1] = KERN_CLOCKRATE;
484	clockrate.profhz = 1;
485	size = sizeof clockrate;
486	if (sysctl(mib, 2, &clockrate, &size, NULL, 0) < 0)
487		warn("get clockrate");
488	return (clockrate.profhz);
489}
490
491/*
492 * Reset the kernel profiling date structures.
493 */
494void
495reset(kvp)
496	struct kvmvars *kvp;
497{
498	char *zbuf;
499	u_long biggest;
500	int mib[3];
501
502	setprof(kvp, GMON_PROF_OFF);
503
504	biggest = kvp->gpm.kcountsize;
505	if (kvp->gpm.fromssize > biggest)
506		biggest = kvp->gpm.fromssize;
507	if (kvp->gpm.tossize > biggest)
508		biggest = kvp->gpm.tossize;
509	if ((zbuf = (char *)malloc(biggest)) == NULL)
510		errx(12, "cannot allocate zbuf space");
511	bzero(zbuf, biggest);
512	if (kflag) {
513		if (kvm_write(kvp->kd, (u_long)kvp->gpm.kcount, zbuf,
514		    kvp->gpm.kcountsize) != kvp->gpm.kcountsize)
515			errx(13, "tickbuf zero: %s", kvm_geterr(kvp->kd));
516		if (kvm_write(kvp->kd, (u_long)kvp->gpm.froms, zbuf,
517		    kvp->gpm.fromssize) != kvp->gpm.fromssize)
518			errx(14, "froms zero: %s", kvm_geterr(kvp->kd));
519		if (kvm_write(kvp->kd, (u_long)kvp->gpm.tos, zbuf,
520		    kvp->gpm.tossize) != kvp->gpm.tossize)
521			errx(15, "tos zero: %s", kvm_geterr(kvp->kd));
522		return;
523	}
524	(void)seteuid(0);
525	mib[0] = CTL_KERN;
526	mib[1] = KERN_PROF;
527	mib[2] = GPROF_COUNT;
528	if (sysctl(mib, 3, NULL, NULL, zbuf, kvp->gpm.kcountsize) < 0)
529		err(13, "tickbuf zero");
530	mib[2] = GPROF_FROMS;
531	if (sysctl(mib, 3, NULL, NULL, zbuf, kvp->gpm.fromssize) < 0)
532		err(14, "froms zero");
533	mib[2] = GPROF_TOS;
534	if (sysctl(mib, 3, NULL, NULL, zbuf, kvp->gpm.tossize) < 0)
535		err(15, "tos zero");
536	(void)seteuid(getuid());
537	free(zbuf);
538}
539