1/*-
2 * Copyright (c) 1980, 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 * 4. Neither the name of the University nor the names of its contributors
14 *    may be used to endorse or promote products derived from this software
15 *    without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 */
29
30#include <sys/cdefs.h>
31
32__FBSDID("$FreeBSD: stable/11/usr.bin/systat/main.c 368931 2021-01-05 20:02:55Z mr $");
33
34#ifdef lint
35static const char sccsid[] = "@(#)main.c	8.1 (Berkeley) 6/6/93";
36#endif
37
38#ifndef lint
39static const char copyright[] =
40"@(#) Copyright (c) 1980, 1992, 1993\n\
41	The Regents of the University of California.  All rights reserved.\n";
42#endif
43
44#include <sys/param.h>
45#include <sys/time.h>
46#include <sys/sysctl.h>
47#include <sys/queue.h>
48
49#include <err.h>
50#include <limits.h>
51#include <locale.h>
52#include <nlist.h>
53#include <paths.h>
54#include <signal.h>
55#include <stdio.h>
56#include <stdlib.h>
57#include <string.h>
58#include <unistd.h>
59
60#include "systat.h"
61#include "extern.h"
62
63static int     dellave;
64
65kvm_t *kd;
66sig_t	sigtstpdfl;
67double avenrun[3];
68int     col;
69unsigned int	delay = 5000000;	/* in microseconds */
70int     verbose = 1;                    /* to report kvm read errs */
71struct	clockinfo clkinfo;
72double	hertz;
73char    c;
74char    *namp;
75char    hostname[MAXHOSTNAMELEN];
76WINDOW  *wnd;
77int     CMDLINE;
78int     use_kvm = 1;
79
80static	WINDOW *wload;			/* one line window for load average */
81
82struct cmdentry {
83	SLIST_ENTRY(cmdentry) link;
84	char		*cmd;		/* Command name	*/
85	char		*argv;		/* Arguments vector for a command */
86};
87SLIST_HEAD(, cmdentry) commands;
88
89static void
90parse_cmd_args (int argc, char **argv)
91{
92	int in_command = 0;
93	struct cmdentry *cmd = NULL;
94	double t;
95
96	while (argc) {
97		if (argv[0][0] == '-') {
98			if (in_command)
99					SLIST_INSERT_HEAD(&commands, cmd, link);
100
101			if (memcmp(argv[0], "--", 3) == 0) {
102				in_command = 0; /*-- ends a command explicitly*/
103				argc --, argv ++;
104				continue;
105			}
106			cmd = calloc(1, sizeof(struct cmdentry));
107			if (cmd == NULL)
108				errx(1, "memory allocating failure");
109			cmd->cmd = strdup(&argv[0][1]);
110			if (cmd->cmd == NULL)
111				errx(1, "memory allocating failure");
112			in_command = 1;
113		}
114		else if (!in_command) {
115			t = strtod(argv[0], NULL) * 1000000.0;
116			if (t > 0 && t < (double)UINT_MAX)
117				delay = (unsigned int)t;
118		}
119		else if (cmd != NULL) {
120			cmd->argv = strdup(argv[0]);
121			if (cmd->argv == NULL)
122				errx(1, "memory allocating failure");
123			in_command = 0;
124			SLIST_INSERT_HEAD(&commands, cmd, link);
125		}
126		else
127			errx(1, "invalid arguments list");
128
129		argc--, argv++;
130	}
131	if (in_command && cmd != NULL)
132		SLIST_INSERT_HEAD(&commands, cmd, link);
133
134}
135
136int
137main(int argc, char **argv)
138{
139	char errbuf[_POSIX2_LINE_MAX], dummy;
140	size_t	size;
141	struct cmdentry *cmd = NULL;
142
143	(void) setlocale(LC_ALL, "");
144
145	SLIST_INIT(&commands);
146	argc--, argv++;
147	if (argc > 0) {
148		if (argv[0][0] == '-') {
149			struct cmdtab *p;
150
151			p = lookup(&argv[0][1]);
152			if (p == (struct cmdtab *)-1)
153				errx(1, "%s: ambiguous request", &argv[0][1]);
154			if (p == (struct cmdtab *)0)
155				errx(1, "%s: unknown request", &argv[0][1]);
156			curcmd = p;
157			argc--, argv++;
158		}
159		parse_cmd_args (argc, argv);
160
161	}
162	kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
163	if (kd != NULL) {
164		/*
165		 * Try to actually read something, we may be in a jail, and
166		 * have /dev/null opened as /dev/mem.
167		 */
168		if (kvm_nlist(kd, namelist) != 0 || namelist[0].n_value == 0 ||
169		    kvm_read(kd, namelist[0].n_value, &dummy, sizeof(dummy)) !=
170		    sizeof(dummy)) {
171			kvm_close(kd);
172			kd = NULL;
173		}
174	}
175	if (kd == NULL) {
176		/*
177		 * Maybe we are lacking permissions? Retry, this time with bogus
178		 * devices. We can now use sysctl only.
179		 */
180		use_kvm = 0;
181		kd = kvm_openfiles(_PATH_DEVNULL, _PATH_DEVNULL, _PATH_DEVNULL,
182		    O_RDONLY, errbuf);
183		if (kd == NULL) {
184			error("%s", errbuf);
185			exit(1);
186		}
187	}
188	signal(SIGHUP, die);
189	signal(SIGINT, die);
190	signal(SIGQUIT, die);
191	signal(SIGTERM, die);
192
193	/*
194	 * Initialize display.  Load average appears in a one line
195	 * window of its own.  Current command's display appears in
196	 * an overlapping sub-window of stdscr configured by the display
197	 * routines to minimize update work by curses.
198	 */
199	initscr();
200	CMDLINE = LINES - 1;
201	wnd = (*curcmd->c_open)();
202	if (wnd == NULL) {
203		warnx("couldn't initialize display");
204		die(0);
205	}
206	wload = newwin(1, 0, 1, 20);
207	if (wload == NULL) {
208		warnx("couldn't set up load average window");
209		die(0);
210	}
211	gethostname(hostname, sizeof (hostname));
212	size = sizeof(clkinfo);
213	if (sysctlbyname("kern.clockrate", &clkinfo, &size, NULL, 0)
214	    || size != sizeof(clkinfo)) {
215		error("kern.clockrate");
216		die(0);
217	}
218	hertz = clkinfo.stathz;
219	(*curcmd->c_init)();
220	curcmd->c_flags |= CF_INIT;
221	labels();
222
223	if (curcmd->c_cmd != NULL)
224		SLIST_FOREACH (cmd, &commands, link)
225			if (!curcmd->c_cmd(cmd->cmd, cmd->argv))
226				warnx("command is not understood");
227
228	dellave = 0.0;
229	display();
230	noecho();
231	crmode();
232	keyboard();
233	/*NOTREACHED*/
234
235	return EXIT_SUCCESS;
236}
237
238void
239labels(void)
240{
241	if (curcmd->c_flags & CF_LOADAV) {
242		mvaddstr(0, 20,
243		    "/0   /1   /2   /3   /4   /5   /6   /7   /8   /9   /10");
244		mvaddstr(1, 5, "Load Average");
245	}
246	if (curcmd->c_flags & CF_ZFSARC) {
247		mvaddstr(0, 20,
248		    "   Total     MFU     MRU    Anon     Hdr   L2Hdr   Other");
249		mvaddstr(1, 5, "ZFS ARC     ");
250	}
251	(*curcmd->c_label)();
252#ifdef notdef
253	mvprintw(21, 25, "CPU usage on %s", hostname);
254#endif
255	refresh();
256}
257
258void
259display(void)
260{
261	int i, j;
262
263	/* Get the load average over the last minute. */
264	(void) getloadavg(avenrun, nitems(avenrun));
265	(*curcmd->c_fetch)();
266	if (curcmd->c_flags & CF_LOADAV) {
267		j = 5.0*avenrun[0] + 0.5;
268		dellave -= avenrun[0];
269		if (dellave >= 0.0)
270			c = '<';
271		else {
272			c = '>';
273			dellave = -dellave;
274		}
275		if (dellave < 0.1)
276			c = '|';
277		dellave = avenrun[0];
278		wmove(wload, 0, 0); wclrtoeol(wload);
279		for (i = MIN(j, 50); i > 0; i--)
280			waddch(wload, c);
281		if (j > 50)
282			wprintw(wload, " %4.1f", avenrun[0]);
283	}
284	if (curcmd->c_flags & CF_ZFSARC) {
285	    uint64_t arc[7] = {};
286	    size_t size = sizeof(arc[0]);
287	    if (sysctlbyname("kstat.zfs.misc.arcstats.size",
288		&arc[0], &size, NULL, 0) == 0 ) {
289		    GETSYSCTL("vfs.zfs.mfu_size", arc[1]);
290		    GETSYSCTL("vfs.zfs.mru_size", arc[2]);
291		    GETSYSCTL("vfs.zfs.anon_size", arc[3]);
292		    GETSYSCTL("kstat.zfs.misc.arcstats.hdr_size", arc[4]);
293		    GETSYSCTL("kstat.zfs.misc.arcstats.l2_hdr_size", arc[5]);
294		    GETSYSCTL("kstat.zfs.misc.arcstats.other_size", arc[6]);
295		    wmove(wload, 0, 0); wclrtoeol(wload);
296		    for (i = 0 ; i < nitems(arc); i++)
297			sysputuint64(wload, 0, i*8+2, 6, arc[i], 0);
298	    }
299	}
300	(*curcmd->c_refresh)();
301	if (curcmd->c_flags & (CF_LOADAV |CF_ZFSARC))
302		wrefresh(wload);
303	wrefresh(wnd);
304	move(CMDLINE, col);
305	refresh();
306}
307
308void
309load(void)
310{
311
312	(void) getloadavg(avenrun, nitems(avenrun));
313	mvprintw(CMDLINE, 0, "%4.1f %4.1f %4.1f",
314	    avenrun[0], avenrun[1], avenrun[2]);
315	clrtoeol();
316}
317
318void
319die(int signo __unused)
320{
321	move(CMDLINE, 0);
322	clrtoeol();
323	refresh();
324	endwin();
325	exit(0);
326}
327
328#include <stdarg.h>
329
330void
331error(const char *fmt, ...)
332{
333	va_list ap;
334	char buf[255];
335	int oy, ox;
336
337	va_start(ap, fmt);
338	if (wnd) {
339		getyx(stdscr, oy, ox);
340		(void) vsnprintf(buf, sizeof(buf), fmt, ap);
341		clrtoeol();
342		standout();
343		mvaddstr(CMDLINE, 0, buf);
344		standend();
345		move(oy, ox);
346		refresh();
347	} else {
348		(void) vfprintf(stderr, fmt, ap);
349		fprintf(stderr, "\n");
350	}
351	va_end(ap);
352}
353
354void
355nlisterr(struct nlist n_list[])
356{
357	int i, n;
358
359	n = 0;
360	clear();
361	mvprintw(2, 10, "systat: nlist: can't find following symbols:");
362	for (i = 0;
363	    n_list[i].n_name != NULL && *n_list[i].n_name != '\0'; i++)
364		if (n_list[i].n_value == 0)
365			mvprintw(2 + ++n, 10, "%s", n_list[i].n_name);
366	move(CMDLINE, 0);
367	clrtoeol();
368	refresh();
369	endwin();
370	exit(1);
371}
372