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