xref: /netbsd-src/usr.bin/systat/main.c (revision 5bbd2a12505d72a8177929a37b5cee489d0a1cfd)
1 /*	$NetBSD: main.c,v 1.46 2011/09/06 18:31:44 joerg Exp $	*/
2 
3 /*-
4  * Copyright (c) 1980, 1992, 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 
32 #include <sys/cdefs.h>
33 #ifndef lint
34 __COPYRIGHT("@(#) Copyright (c) 1980, 1992, 1993\
35  The Regents of the University of California.  All rights reserved.");
36 #if 0
37 static char sccsid[] = "@(#)main.c	8.1 (Berkeley) 6/6/93";
38 #endif
39 __RCSID("$NetBSD: main.c,v 1.46 2011/09/06 18:31:44 joerg Exp $");
40 #endif /* not lint */
41 
42 #include <sys/param.h>
43 
44 #include <ctype.h>
45 #include <err.h>
46 #include <limits.h>
47 #include <signal.h>
48 #include <stdarg.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <unistd.h>
53 #include <termios.h>
54 #include <sys/ioctl.h>
55 
56 #include "systat.h"
57 #include "extern.h"
58 
59 static struct nlist namelist[] = {
60 #define X_FIRST		0
61 #define	X_HZ		0
62 	{ .n_name = "_hz" },
63 #define	X_STATHZ		1
64 	{ .n_name = "_stathz" },
65 #define	X_MAXSLP		2
66 	{ .n_name = "_maxslp" },
67 	{ .n_name = NULL }
68 };
69 static int     dellave;
70 
71 kvm_t *kd;
72 char	*memf = NULL;
73 char	*nlistf = NULL;
74 sig_t	sigtstpdfl;
75 double avenrun[3];
76 int     col;
77 int	naptime = 5;
78 int     verbose = 1;                    /* to report kvm read errs */
79 int     hz, stathz, maxslp;
80 char    c;
81 char    *namp;
82 char    hostname[MAXHOSTNAMELEN + 1];
83 WINDOW  *wnd;
84 int     CMDLINE;
85 int     turns = 2;	/* stay how many refresh-turns in 'all' mode? */
86 int     allflag;
87 int     allcounter;
88 sig_atomic_t needsredraw = 0;
89 int	use_sysctl = 1;
90 
91 static	WINDOW *wload;			/* one line window for load average */
92 
93 static void (*sv_stop_handler)(int);
94 
95 static void stop(int);
96 __dead static void usage(void);
97 
98 gid_t egid; /* XXX needed by initiostat() and initkre() */
99 
100 int
101 main(int argc, char **argv)
102 {
103 	int ch;
104 	char errbuf[_POSIX2_LINE_MAX];
105 	const char *all;
106 
107 	all = "all";
108 	egid = getegid();
109 	(void)setegid(getgid());
110 
111 	while ((ch = getopt(argc, argv, "M:N:nw:t:")) != -1)
112 		switch(ch) {
113 		case 'M':
114 			memf = optarg;
115 			use_sysctl = 0;
116 			break;
117 		case 'N':
118 			nlistf = optarg;
119 			break;
120 		case 'n':
121 			nflag = !nflag;
122 			break;
123 		case 'w':
124 			if ((naptime = atoi(optarg)) <= 0)
125 				errx(1, "interval <= 0.");
126 			break;
127 		case 't':
128 			if ((turns = atoi(optarg)) <= 0)
129 				errx(1, "turns <= 0.");
130 			break;
131 		case '?':
132 		default:
133 			usage();
134 		}
135 	argc -= optind;
136 	argv += optind;
137 
138 
139 	for ( ; argc > 0; argc--, argv++) {
140 		struct mode *p;
141 		int modefound = 0;
142 
143 		if (isdigit((unsigned char)argv[0][0])) {
144 			naptime = atoi(argv[0]);
145 			if (naptime <= 0)
146 				naptime = 5;
147 			continue;
148 		}
149 
150 		for (p = modes; p->c_name ; p++) {
151 			if (strstr(p->c_name, argv[0]) == p->c_name) {
152 				curmode = p;
153 				modefound++;
154 				break;
155 			}
156 
157 			if (strstr(all, argv[0]) == all) {
158 				allcounter=0;
159 				allflag=1;
160 			}
161 		}
162 
163 
164 		if (!modefound && !allflag)
165 			error("%s: Unknown command.", argv[0]);
166 	}
167 
168 	/*
169 	 * Discard setgid privileges.  If not the running kernel, we toss
170 	 * them away totally so that bad guys can't print interesting stuff
171 	 * from kernel memory, otherwise switch back to kmem for the
172 	 * duration of the kvm_openfiles() call.
173 	 */
174 	if (nlistf != NULL || memf != NULL)
175 		(void)setgid(getgid());
176 	else
177 		(void)setegid(egid);
178 
179 	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
180 	if (kd == NULL) {
181 		error("%s", errbuf);
182 		exit(1);
183 	}
184 
185 	/* Get rid of privs for now. */
186 	if (nlistf == NULL && memf == NULL)
187 		(void)setegid(getgid());
188 
189 	if (kvm_nlist(kd, namelist)) {
190 		if (nlistf)
191 			errx(1, "%s: no namelist", nlistf);
192 		else
193 			errx(1, "no namelist");
194 	}
195 
196 	signal(SIGINT, die);
197 	signal(SIGQUIT, die);
198 	signal(SIGTERM, die);
199 	sv_stop_handler = signal(SIGTSTP, stop);
200 
201 	/*
202 	 * Initialize display.  Load average appears in a one line
203 	 * window of its own.  Current command's display appears in
204 	 * an overlapping sub-window of stdscr configured by the display
205 	 * routines to minimize update work by curses.
206 	 */
207 	if (initscr() == NULL)
208 	{
209 		warnx("couldn't initialize screen");
210 		exit(0);
211 	}
212 
213 	CMDLINE = LINES - 1;
214 	wnd = (*curmode->c_open)();
215 	if (wnd == NULL) {
216 		warnx("couldn't initialize display");
217 		die(0);
218 	}
219 	wload = newwin(1, 0, 3, 20);
220 	if (wload == NULL) {
221 		warnx("couldn't set up load average window");
222 		die(0);
223 	}
224 	gethostname(hostname, sizeof (hostname));
225 	hostname[sizeof(hostname) - 1] = '\0';
226 	NREAD(X_HZ, &hz, sizeof hz);
227 	NREAD(X_STATHZ, &stathz, sizeof stathz);
228 	NREAD(X_MAXSLP, &maxslp, sizeof maxslp);
229 	(*curmode->c_init)();
230 	curmode->c_flags |= CF_INIT;
231 	labels();
232 
233 	dellave = 0.0;
234 
235 	display(0);
236 	noecho();
237 	cbreak();
238 	keyboard();
239 	/*NOTREACHED*/
240 }
241 
242 static void
243 usage(void)
244 {
245 	fprintf(stderr, "usage: systat [-n] [-M core] [-N system] [-w wait] "
246 		"[-t turns]\n\t\t[display] [refresh-interval]\n");
247 	exit(1);
248 }
249 
250 
251 void
252 labels(void)
253 {
254 	if (curmode->c_flags & CF_LOADAV) {
255 		mvaddstr(2, 20,
256 		    "/0   /1   /2   /3   /4   /5   /6   /7   /8   /9   /10");
257 		mvaddstr(3, 5, "Load Average");
258 	}
259 	(*curmode->c_label)();
260 #ifdef notdef
261 	mvprintw(21, 25, "CPU usage on %s", hostname);
262 #endif
263 	refresh();
264 }
265 
266 void
267 display(int signo)
268 {
269 	static int skip;
270 	int j;
271 	struct mode *p;
272 	int ms_delay;
273 
274 	if (signo == SIGALRM && skip-- > 0)
275 		/* Don't display on this timeout */
276 		return;
277 
278 	/* Get the load average over the last minute. */
279 	(void)getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0]));
280 	(*curmode->c_fetch)();
281 	if (curmode->c_flags & CF_LOADAV) {
282 		j = 5.0*avenrun[0] + 0.5;
283 		dellave -= avenrun[0];
284 		if (dellave >= 0.0)
285 			c = '<';
286 		else {
287 			c = '>';
288 			dellave = -dellave;
289 		}
290 		if (dellave < 0.1)
291 			c = '|';
292 		dellave = avenrun[0];
293 		wmove(wload, 0, 0);
294 		wclrtoeol(wload);
295 		whline(wload, c, (j > 50) ? 50 : j);
296 		if (j > 50)
297 			wprintw(wload, " %4.1f", avenrun[0]);
298 	}
299 	(*curmode->c_refresh)();
300 	if (curmode->c_flags & CF_LOADAV)
301 		wrefresh(wload);
302 	wrefresh(wnd);
303 	move(CMDLINE, col);
304 	refresh();
305 
306 	if (allflag && signo==SIGALRM) {
307 		if (allcounter >= turns){
308 			p = curmode;
309 			p++;
310 			if (p->c_name == NULL)
311 				p = modes;
312 			switch_mode(p);
313 			allcounter=0;
314 		} else
315 			allcounter++;
316 	}
317 
318 	/* curses timeout() uses VTIME, limited to 255 1/10th secs */
319 	ms_delay = naptime * 1000;
320 	if (ms_delay < 25500) {
321 		timeout(ms_delay);
322 		skip = 0;
323 	} else {
324 		skip = ms_delay / 25500;
325 		timeout(ms_delay / (skip + 1));
326 	}
327 }
328 
329 void
330 redraw(void)
331 {
332 	resizeterm(LINES, COLS);
333 	CMDLINE = LINES - 1;
334 	labels();
335 
336 	display(0);
337 	needsredraw = 0;
338 }
339 
340 static void
341 stop(int signo)
342 {
343 	sigset_t set;
344 
345 	signal(SIGTSTP, sv_stop_handler);
346 	/* unblock SIGTSTP */
347 	sigemptyset(&set);
348 	sigaddset(&set, SIGTSTP);
349 	sigprocmask(SIG_UNBLOCK, &set, NULL);
350 	/* stop ourselves */
351 	kill(0, SIGTSTP);
352 	/* must have been restarted */
353 	signal(SIGTSTP, stop);
354 	needsredraw = signo;
355 }
356 
357 void
358 die(int signo)
359 {
360 	move(CMDLINE, 0);
361 	clrtoeol();
362 	refresh();
363 	endwin();
364 	exit(0);
365 }
366 
367 void
368 error(const char *fmt, ...)
369 {
370 	va_list ap;
371 	char buf[255];
372 	int oy, ox;
373 
374 	va_start(ap, fmt);
375 
376 	if (wnd) {
377 		getyx(stdscr, oy, ox);
378 		(void) vsnprintf(buf, sizeof(buf), fmt, ap);
379 		clrtoeol();
380 		standout();
381 		mvaddstr(CMDLINE, 0, buf);
382 		standend();
383 		move(oy, ox);
384 		refresh();
385 	} else {
386 		(void) vfprintf(stderr, fmt, ap);
387 		fprintf(stderr, "\n");
388 	}
389 	va_end(ap);
390 }
391 
392 void
393 nlisterr(struct nlist name_list[])
394 {
395 	int i, n;
396 
397 	n = 0;
398 	clear();
399 	mvprintw(2, 10, "systat: nlist: can't find following symbols:");
400 	for (i = 0;
401 	    name_list[i].n_name != NULL && *name_list[i].n_name != '\0'; i++)
402 		if (name_list[i].n_value == 0)
403 			mvprintw(2 + ++n, 10, "%s", name_list[i].n_name);
404 	move(CMDLINE, 0);
405 	clrtoeol();
406 	refresh();
407 	sleep(5);
408 	endwin();
409 	exit(1);
410 }
411