xref: /freebsd/usr.bin/systat/main.c (revision fd45b686f9d92f583366c75b22c04c7ee49709c0)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
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 
33 
34 #include <sys/param.h>
35 #include <sys/time.h>
36 #include <sys/sysctl.h>
37 #include <sys/queue.h>
38 
39 #include <err.h>
40 #include <limits.h>
41 #include <locale.h>
42 #include <nlist.h>
43 #include <paths.h>
44 #include <signal.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <unistd.h>
49 
50 #include "systat.h"
51 #include "extern.h"
52 
53 static int     dellave;
54 
55 kvm_t *kd;
56 double avenrun[3];
57 int     col;
58 unsigned int	delay = 5000000;	/* in microseconds */
59 int     verbose = 1;                    /* to report kvm read errs */
60 static struct	clockinfo clkinfo;
61 double	hertz;
62 char    c;
63 char    *namp;
64 char    hostname[MAXHOSTNAMELEN];
65 WINDOW  *wnd;
66 int     CMDLINE;
67 int     use_kvm = 1;
68 
69 static	WINDOW *wload;			/* one line window for load average */
70 
71 struct cmdentry {
72 	SLIST_ENTRY(cmdentry) link;
73 	char		*cmd;		/* Command name	*/
74 	char		*argv;		/* Arguments vector for a command */
75 };
76 static SLIST_HEAD(, cmdentry) commands;
77 
78 static void
79 parse_cmd_args (int argc, char **argv)
80 {
81 	int in_command = 0;
82 	struct cmdentry *cmd = NULL;
83 	double t;
84 
85 	while (argc) {
86 		if (argv[0][0] == '-') {
87 			if (in_command)
88 					SLIST_INSERT_HEAD(&commands, cmd, link);
89 
90 			if (memcmp(argv[0], "--", 3) == 0) {
91 				in_command = 0; /*-- ends a command explicitly*/
92 				argc --, argv ++;
93 				continue;
94 			}
95 			cmd = calloc(1, sizeof(struct cmdentry));
96 			if (cmd == NULL)
97 				errx(1, "memory allocating failure");
98 			cmd->cmd = strdup(&argv[0][1]);
99 			if (cmd->cmd == NULL)
100 				errx(1, "memory allocating failure");
101 			in_command = 1;
102 		}
103 		else if (!in_command) {
104 			t = strtod(argv[0], NULL) * 1000000.0;
105 			if (t > 0 && t < (double)UINT_MAX)
106 				delay = (unsigned int)t;
107 		}
108 		else if (cmd != NULL) {
109 			cmd->argv = strdup(argv[0]);
110 			if (cmd->argv == NULL)
111 				errx(1, "memory allocating failure");
112 			in_command = 0;
113 			SLIST_INSERT_HEAD(&commands, cmd, link);
114 		}
115 		else
116 			errx(1, "invalid arguments list");
117 
118 		argc--, argv++;
119 	}
120 	if (in_command && cmd != NULL)
121 		SLIST_INSERT_HEAD(&commands, cmd, link);
122 
123 }
124 
125 static void
126 resize(int signo __unused)
127 {
128 
129 	endwin();
130 	refresh();
131 	clear();
132 
133 	CMDLINE = LINES - 1;
134 	labels();
135 	display();
136 	status();
137 }
138 
139 
140 int
141 main(int argc, char **argv)
142 {
143 	char errbuf[_POSIX2_LINE_MAX], dummy;
144 	size_t	size;
145 	struct cmdentry *cmd = NULL;
146 	short cf, cb;
147 
148 	(void) setlocale(LC_ALL, "");
149 
150 	SLIST_INIT(&commands);
151 	argc--, argv++;
152 	if (argc > 0) {
153 		if (argv[0][0] == '-') {
154 			struct cmdtab *p;
155 
156 			p = lookup(&argv[0][1]);
157 			if (p == (struct cmdtab *)-1)
158 				errx(1, "%s: ambiguous request", &argv[0][1]);
159 			if (p == (struct cmdtab *)0)
160 				errx(1, "%s: unknown request", &argv[0][1]);
161 			curcmd = p;
162 			argc--, argv++;
163 		}
164 		parse_cmd_args (argc, argv);
165 
166 	}
167 	kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
168 	if (kd != NULL) {
169 		/*
170 		 * Try to actually read something, we may be in a jail, and
171 		 * have /dev/null opened as /dev/mem.
172 		 */
173 		if (kvm_nlist(kd, namelist) != 0 || namelist[0].n_value == 0 ||
174 		    kvm_read(kd, namelist[0].n_value, &dummy, sizeof(dummy)) !=
175 		    sizeof(dummy)) {
176 			kvm_close(kd);
177 			kd = NULL;
178 		}
179 	}
180 	if (kd == NULL) {
181 		/*
182 		 * Maybe we are lacking permissions? Retry, this time with bogus
183 		 * devices. We can now use sysctl only.
184 		 */
185 		use_kvm = 0;
186 		kd = kvm_openfiles(_PATH_DEVNULL, _PATH_DEVNULL, _PATH_DEVNULL,
187 		    O_RDONLY, errbuf);
188 		if (kd == NULL) {
189 			error("%s", errbuf);
190 			exit(1);
191 		}
192 	}
193 	signal(SIGHUP, die);
194 	signal(SIGINT, die);
195 	signal(SIGQUIT, die);
196 	signal(SIGTERM, die);
197 	signal(SIGWINCH, resize);
198 
199 	/*
200 	 * Initialize display.  Load average appears in a one line
201 	 * window of its own.  Current command's display appears in
202 	 * an overlapping sub-window of stdscr configured by the display
203 	 * routines to minimize update work by curses.
204 	 */
205 	initscr();
206 	start_color();
207 	use_default_colors();
208 	pair_content(0, &cf, &cb);
209 	init_pair(1, COLOR_GREEN, cb);
210 	init_pair(2, COLOR_MAGENTA, cb);
211 	init_pair(3, COLOR_RED, cb);
212 	init_pair(4, COLOR_BLUE, cb);
213 	CMDLINE = LINES - 1;
214 	wnd = (*curcmd->c_open)();
215 	if (wnd == NULL) {
216 		warnx("couldn't initialize display");
217 		die(0);
218 	}
219 	wload = newwin(1, 0, 1, 20);
220 	if (wload == NULL) {
221 		warnx("couldn't set up load average window");
222 		die(0);
223 	}
224 	gethostname(hostname, sizeof (hostname));
225 	size = sizeof(clkinfo);
226 	if (sysctlbyname("kern.clockrate", &clkinfo, &size, NULL, 0)
227 	    || size != sizeof(clkinfo)) {
228 		error("kern.clockrate");
229 		die(0);
230 	}
231 	hertz = clkinfo.stathz;
232 	(*curcmd->c_init)();
233 	curcmd->c_flags |= CF_INIT;
234 	labels();
235 
236 	if (curcmd->c_cmd != NULL)
237 		SLIST_FOREACH (cmd, &commands, link)
238 			if (!curcmd->c_cmd(cmd->cmd, cmd->argv))
239 				warnx("command is not understood");
240 
241 	dellave = 0.0;
242 	display();
243 	noecho();
244 	crmode();
245 	keyboard();
246 	/*NOTREACHED*/
247 
248 	return EXIT_SUCCESS;
249 }
250 
251 void
252 labels(void)
253 {
254 	if (curcmd->c_flags & CF_LOADAV) {
255 		mvaddstr(0, 20,
256 		    "/0   /1   /2   /3   /4   /5   /6   /7   /8   /9   /10");
257 		mvaddstr(1, 5, "Load Average");
258 	}
259 	if (curcmd->c_flags & CF_ZFSARC) {
260 		mvaddstr(0, 20,
261 		    "   Total     MFU     MRU    Anon     Hdr   L2Hdr   Other");
262 		mvaddstr(1, 5, "ZFS ARC     ");
263 	}
264 	(*curcmd->c_label)();
265 #ifdef notdef
266 	mvprintw(21, 25, "CPU usage on %s", hostname);
267 #endif
268 	refresh();
269 }
270 
271 void
272 display(void)
273 {
274 	uint64_t arc_stat;
275 	unsigned int ui;
276 	int i, j;
277 
278 	/* Get the load average over the last minute. */
279 	(void) getloadavg(avenrun, nitems(avenrun));
280 	(*curcmd->c_fetch)();
281 	if (curcmd->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); wclrtoeol(wload);
294 		for (i = MIN(j, 50); i > 0; i--)
295 			waddch(wload, c);
296 		if (j > 50)
297 			wprintw(wload, " %4.1f", avenrun[0]);
298 	}
299 	if (curcmd->c_flags & CF_ZFSARC) {
300 	    uint64_t arc[7] = {};
301 	    size_t size = sizeof(arc[0]);
302 	    if (sysctlbyname("kstat.zfs.misc.arcstats.size",
303 		&arc[0], &size, NULL, 0) == 0 ) {
304 		    GETSYSCTL("vfs.zfs.mfu_size", arc[1]);
305 		    GETSYSCTL("vfs.zfs.mru_size", arc[2]);
306 		    GETSYSCTL("vfs.zfs.anon_size", arc[3]);
307 		    GETSYSCTL("kstat.zfs.misc.arcstats.hdr_size", arc[4]);
308 		    GETSYSCTL("kstat.zfs.misc.arcstats.l2_hdr_size", arc[5]);
309 		    GETSYSCTL("kstat.zfs.misc.arcstats.bonus_size", arc[6]);
310 		    GETSYSCTL("kstat.zfs.misc.arcstats.dnode_size", arc_stat);
311 		    arc[6] += arc_stat;
312 		    GETSYSCTL("kstat.zfs.misc.arcstats.dbuf_size", arc_stat);
313 		    arc[6] += arc_stat;
314 		    wmove(wload, 0, 0); wclrtoeol(wload);
315 		    for (ui = 0 ; ui < nitems(arc); ui++)
316 			sysputuint64(wload, 0, ui*8+2, 6, arc[ui], 0);
317 	    }
318 	}
319 	(*curcmd->c_refresh)();
320 	if (curcmd->c_flags & (CF_LOADAV |CF_ZFSARC))
321 		wrefresh(wload);
322 	wrefresh(wnd);
323 	move(CMDLINE, col);
324 	refresh();
325 }
326 
327 void
328 load(void)
329 {
330 
331 	(void) getloadavg(avenrun, nitems(avenrun));
332 	mvprintw(CMDLINE, 0, "%4.1f %4.1f %4.1f",
333 	    avenrun[0], avenrun[1], avenrun[2]);
334 	clrtoeol();
335 }
336 
337 void
338 die(int signo __unused)
339 {
340 	move(CMDLINE, 0);
341 	clrtoeol();
342 	refresh();
343 	endwin();
344 	exit(0);
345 }
346 
347 #include <stdarg.h>
348 
349 void
350 error(const char *fmt, ...)
351 {
352 	va_list ap;
353 	char buf[255];
354 	int oy, ox;
355 
356 	va_start(ap, fmt);
357 	if (wnd) {
358 		getyx(stdscr, oy, ox);
359 		(void) vsnprintf(buf, sizeof(buf), fmt, ap);
360 		clrtoeol();
361 		standout();
362 		mvaddstr(CMDLINE, 0, buf);
363 		standend();
364 		move(oy, ox);
365 		refresh();
366 	} else {
367 		(void) vfprintf(stderr, fmt, ap);
368 		fprintf(stderr, "\n");
369 	}
370 	va_end(ap);
371 }
372 
373 void
374 nlisterr(struct nlist n_list[])
375 {
376 	int i, n;
377 
378 	n = 0;
379 	clear();
380 	mvprintw(2, 10, "systat: nlist: can't find following symbols:");
381 	for (i = 0;
382 	    n_list[i].n_name != NULL && *n_list[i].n_name != '\0'; i++)
383 		if (n_list[i].n_value == 0)
384 			mvprintw(2 + ++n, 10, "%s", n_list[i].n_name);
385 	move(CMDLINE, 0);
386 	clrtoeol();
387 	refresh();
388 	endwin();
389 	exit(1);
390 }
391