xref: /freebsd/usr.sbin/pstat/pstat.c (revision 8aac90f18aef7c9eea906c3ff9a001ca7b94f375)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1980, 1991, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  * Copyright (c) 2002 Networks Associates Technologies, Inc.
7  * All rights reserved.
8  *
9  * Portions of this software were developed for the FreeBSD Project by
10  * ThinkSec AS and NAI Labs, the Security Research Division of Network
11  * Associates, Inc.  under DARPA/SPAWAR contract N66001-01-C-8035
12  * ("CBOSS"), as part of the DARPA CHATS research program.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  */
38 
39 #include <sys/param.h>
40 #include <sys/time.h>
41 #include <sys/file.h>
42 #include <sys/stat.h>
43 #include <sys/stdint.h>
44 #include <sys/ioctl.h>
45 #include <sys/tty.h>
46 #include <sys/blist.h>
47 
48 #include <sys/sysctl.h>
49 #include <vm/vm_param.h>
50 
51 #include <err.h>
52 #include <errno.h>
53 #include <fcntl.h>
54 #include <kvm.h>
55 #include <libutil.h>
56 #include <limits.h>
57 #include <nlist.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <unistd.h>
62 
63 enum {
64 	NL_CONSTTY,
65 	NL_MAXFILES,
66 	NL_NFILES,
67 	NL_TTY_LIST,
68 	NL_MARKER
69 };
70 
71 static struct {
72 	int order;
73 	const char *name;
74 } namelist[] = {
75 	{ NL_CONSTTY, "_constty" },
76 	{ NL_MAXFILES, "_maxfiles" },
77 	{ NL_NFILES, "_openfiles" },
78 	{ NL_TTY_LIST, "_tty_list" },
79 	{ NL_MARKER, "" },
80 };
81 #define NNAMES	(sizeof(namelist) / sizeof(*namelist))
82 static struct nlist nl[NNAMES];
83 
84 #define	SIZEHDR	"Size"
85 
86 static int	humanflag;
87 static int	usenumflag;
88 static int	totalflag;
89 static int	swapflag;
90 static char	*nlistf;
91 static char	*memf;
92 static kvm_t	*kd;
93 
94 static const char *usagestr;
95 
96 static void	filemode(void);
97 static int	getfiles(struct xfile **, size_t *);
98 static void	swapmode(void);
99 static void	ttymode(void);
100 static void	ttyprt(struct xtty *);
101 static void	usage(void);
102 
103 int
104 main(int argc, char *argv[])
105 {
106 	int ch, quit, ret;
107 	int fileflag, ttyflag;
108 	unsigned int i;
109 	char buf[_POSIX2_LINE_MAX];
110 	const char *opts;
111 
112 	fileflag = swapflag = ttyflag = 0;
113 
114 	/* We will behave like good old swapinfo if thus invoked */
115 	opts = strrchr(argv[0], '/');
116 	if (opts)
117 		opts++;
118 	else
119 		opts = argv[0];
120 	if (!strcmp(opts, "swapinfo")) {
121 		swapflag = 1;
122 		opts = "ghkmM:N:";
123 		usagestr = "swapinfo [-ghkm] [-M core [-N system]]";
124 	} else {
125 		opts = "TM:N:fghkmnst";
126 		usagestr = "pstat [-Tfghkmnst] [-M core [-N system]]";
127 	}
128 
129 	while ((ch = getopt(argc, argv, opts)) != -1)
130 		switch (ch) {
131 		case 'f':
132 			fileflag = 1;
133 			break;
134 		case 'g':
135 			setenv("BLOCKSIZE", "1G", 1);
136 			break;
137 		case 'h':
138 			humanflag = 1;
139 			break;
140 		case 'k':
141 			setenv("BLOCKSIZE", "1K", 1);
142 			break;
143 		case 'm':
144 			setenv("BLOCKSIZE", "1M", 1);
145 			break;
146 		case 'M':
147 			memf = optarg;
148 			break;
149 		case 'N':
150 			nlistf = optarg;
151 			break;
152 		case 'n':
153 			usenumflag = 1;
154 			break;
155 		case 's':
156 			++swapflag;
157 			break;
158 		case 'T':
159 			totalflag = 1;
160 			break;
161 		case 't':
162 			ttyflag = 1;
163 			break;
164 		default:
165 			usage();
166 		}
167 
168 	/*
169 	 * Initialize symbol names list.
170 	 */
171 	for (i = 0; i < NNAMES; i++)
172 		nl[namelist[i].order].n_name = strdup(namelist[i].name);
173 
174 	if (memf != NULL) {
175 		kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, buf);
176 		if (kd == NULL)
177 			errx(1, "kvm_openfiles: %s", buf);
178 		if ((ret = kvm_nlist(kd, nl)) != 0) {
179 			if (ret == -1)
180 				errx(1, "kvm_nlist: %s", kvm_geterr(kd));
181 			quit = 0;
182 			for (i = 0; nl[i].n_name[0] != '\0'; ++i)
183 				if (nl[i].n_value == 0) {
184 					quit = 1;
185 					warnx("undefined symbol: %s",
186 					    nl[i].n_name);
187 				}
188 			if (quit)
189 				exit(1);
190 		}
191 	}
192 	if (!(fileflag | ttyflag | swapflag | totalflag))
193 		usage();
194 	if (fileflag || totalflag)
195 		filemode();
196 	if (ttyflag)
197 		ttymode();
198 	if (swapflag || totalflag)
199 		swapmode();
200 	exit (0);
201 }
202 
203 static void
204 usage(void)
205 {
206 	fprintf(stderr, "usage: %s\n", usagestr);
207 	exit (1);
208 }
209 
210 static const char fhdr32[] =
211   "   LOC   TYPE   FLG  CNT MSG   DATA        OFFSET\n";
212 /* c0000000 ------ RWAI 123 123 c0000000 1000000000000000 */
213 
214 static const char fhdr64[] =
215   "       LOC       TYPE   FLG  CNT MSG       DATA            OFFSET\n";
216 /* c000000000000000 ------ RWAI 123 123 c000000000000000 1000000000000000 */
217 
218 static const char hdr[] =
219 "      LINE   INQ  CAN  LIN  LOW  OUTQ  USE  LOW   COL  SESS  PGID STATE\n";
220 
221 static void
222 ttymode_kvm(void)
223 {
224 	TAILQ_HEAD(, tty) tl;
225 	struct tty *tp, tty;
226 	struct xtty xt;
227 
228 	(void)printf("%s", hdr);
229 	bzero(&xt, sizeof xt);
230 	xt.xt_size = sizeof xt;
231 	if (kvm_read(kd, nl[NL_TTY_LIST].n_value, &tl, sizeof tl) != sizeof tl)
232 		errx(1, "kvm_read(): %s", kvm_geterr(kd));
233 	tp = TAILQ_FIRST(&tl);
234 	while (tp != NULL) {
235 		if (kvm_read(kd, (u_long)tp, &tty, sizeof tty) != sizeof tty)
236 			errx(1, "kvm_read(): %s", kvm_geterr(kd));
237 		xt.xt_insize = tty.t_inq.ti_nblocks * TTYINQ_DATASIZE;
238 		xt.xt_incc = tty.t_inq.ti_linestart - tty.t_inq.ti_begin;
239 		xt.xt_inlc = tty.t_inq.ti_end - tty.t_inq.ti_linestart;
240 		xt.xt_inlow = tty.t_inlow;
241 		xt.xt_outsize = tty.t_outq.to_nblocks * TTYOUTQ_DATASIZE;
242 		xt.xt_outcc = tty.t_outq.to_end - tty.t_outq.to_begin;
243 		xt.xt_outlow = tty.t_outlow;
244 		xt.xt_column = tty.t_column;
245 		/* xt.xt_pgid = ... */
246 		/* xt.xt_sid = ... */
247 		xt.xt_flags = tty.t_flags;
248 		xt.xt_dev = (uint32_t)NODEV;
249 		ttyprt(&xt);
250 		tp = TAILQ_NEXT(&tty, t_list);
251 	}
252 }
253 
254 static void
255 ttymode_sysctl(void)
256 {
257 	struct xtty *xttys;
258 	size_t len;
259 	unsigned int i, n;
260 
261 	(void)printf("%s", hdr);
262 	if ((xttys = malloc(len = sizeof(*xttys))) == NULL)
263 		err(1, "malloc()");
264 	while (sysctlbyname("kern.ttys", xttys, &len, 0, 0) == -1) {
265 		if (errno != ENOMEM)
266 			err(1, "sysctlbyname()");
267 		len *= 2;
268 		if ((xttys = realloc(xttys, len)) == NULL)
269 			err(1, "realloc()");
270 	}
271 	n = len / sizeof(*xttys);
272 	for (i = 0; i < n; i++)
273 		ttyprt(&xttys[i]);
274 }
275 
276 static void
277 ttymode(void)
278 {
279 
280 	if (kd != NULL)
281 		ttymode_kvm();
282 	else
283 		ttymode_sysctl();
284 }
285 
286 static struct {
287 	int flag;
288 	char val;
289 } ttystates[] = {
290 #if 0
291 	{ TF_NOPREFIX,		'N' },
292 #endif
293 	{ TF_INITLOCK,		'I' },
294 	{ TF_CALLOUT,		'C' },
295 
296 	/* Keep these together -> 'Oi' and 'Oo'. */
297 	{ TF_OPENED,		'O' },
298 	{ TF_OPENED_IN,		'i' },
299 	{ TF_OPENED_OUT,	'o' },
300 	{ TF_OPENED_CONS,	'c' },
301 
302 	{ TF_GONE,		'G' },
303 	{ TF_OPENCLOSE,		'B' },
304 	{ TF_ASYNC,		'Y' },
305 	{ TF_LITERAL,		'L' },
306 
307 	/* Keep these together -> 'Hi' and 'Ho'. */
308 	{ TF_HIWAT,		'H' },
309 	{ TF_HIWAT_IN,		'i' },
310 	{ TF_HIWAT_OUT,		'o' },
311 
312 	{ TF_STOPPED,		'S' },
313 	{ TF_EXCLUDE,		'X' },
314 	{ TF_BYPASS,		'l' },
315 	{ TF_ZOMBIE,		'Z' },
316 	{ TF_HOOK,		's' },
317 
318 	/* Keep these together -> 'bi' and 'bo'. */
319 	{ TF_BUSY,		'b' },
320 	{ TF_BUSY_IN,		'i' },
321 	{ TF_BUSY_OUT,		'o' },
322 
323 	{ 0,			'\0'},
324 };
325 
326 static void
327 ttyprt(struct xtty *xt)
328 {
329 	int i, j;
330 	const char *name;
331 
332 	if (xt->xt_size != sizeof *xt)
333 		errx(1, "struct xtty size mismatch");
334 	if (usenumflag || xt->xt_dev == 0 ||
335 	   (name = devname(xt->xt_dev, S_IFCHR)) == NULL)
336 		printf("%#10jx ", (uintmax_t)xt->xt_dev);
337 	else
338 		printf("%10s ", name);
339 	printf("%5zu %4zu %4zu %4zu %5zu %4zu %4zu %5u %5d %5d ",
340 	    xt->xt_insize, xt->xt_incc, xt->xt_inlc,
341 	    (xt->xt_insize - xt->xt_inlow), xt->xt_outsize,
342 	    xt->xt_outcc, (xt->xt_outsize - xt->xt_outlow),
343 	    MIN(xt->xt_column, 99999), xt->xt_sid, xt->xt_pgid);
344 	for (i = j = 0; ttystates[i].flag; i++)
345 		if (xt->xt_flags & ttystates[i].flag) {
346 			putchar(ttystates[i].val);
347 			j++;
348 		}
349 	if (j == 0)
350 		putchar('-');
351 	putchar('\n');
352 }
353 
354 static void
355 filemode(void)
356 {
357 	struct xfile *fp, *buf;
358 	char flagbuf[16], *fbp;
359 	int maxf, openf;
360 	size_t len;
361 	static char const * const dtypes[] = { "???", "inode", "socket",
362 	    "pipe", "fifo", "kqueue", "crypto" };
363 	int i;
364 	int wid;
365 
366 	if (kd != NULL) {
367 		if (kvm_read(kd, nl[NL_MAXFILES].n_value,
368 			&maxf, sizeof maxf) != sizeof maxf ||
369 		    kvm_read(kd, nl[NL_NFILES].n_value,
370 			&openf, sizeof openf) != sizeof openf)
371 			errx(1, "kvm_read(): %s", kvm_geterr(kd));
372 	} else {
373 		len = sizeof(int);
374 		if (sysctlbyname("kern.maxfiles", &maxf, &len, 0, 0) == -1 ||
375 		    sysctlbyname("kern.openfiles", &openf, &len, 0, 0) == -1)
376 			err(1, "sysctlbyname()");
377 	}
378 
379 	if (totalflag) {
380 		(void)printf("%3d/%3d files\n", openf, maxf);
381 		return;
382 	}
383 	if (getfiles(&buf, &len) == -1)
384 		return;
385 	openf = len / sizeof *fp;
386 
387 	(void)printf("%d/%d open files\n", openf, maxf);
388 	printf(sizeof(uintptr_t) == 4 ? fhdr32 : fhdr64);
389 	wid = (int)sizeof(uintptr_t) * 2;
390 	for (fp = (struct xfile *)buf, i = 0; i < openf; ++fp, ++i) {
391 		if ((size_t)fp->xf_type >= nitems(dtypes))
392 			continue;
393 		(void)printf("%*jx", wid, (uintmax_t)(uintptr_t)fp->xf_file);
394 		(void)printf(" %-6.6s", dtypes[fp->xf_type]);
395 		fbp = flagbuf;
396 		if (fp->xf_flag & FREAD)
397 			*fbp++ = 'R';
398 		if (fp->xf_flag & FWRITE)
399 			*fbp++ = 'W';
400 		if (fp->xf_flag & FAPPEND)
401 			*fbp++ = 'A';
402 		if (fp->xf_flag & FASYNC)
403 			*fbp++ = 'I';
404 		*fbp = '\0';
405 		(void)printf(" %4s %3d", flagbuf, fp->xf_count);
406 		(void)printf(" %3d", fp->xf_msgcount);
407 		(void)printf(" %*jx", wid, (uintmax_t)(uintptr_t)fp->xf_data);
408 		(void)printf(" %*jx\n", (int)sizeof(fp->xf_offset) * 2,
409 		    (uintmax_t)fp->xf_offset);
410 	}
411 	free(buf);
412 }
413 
414 static int
415 getfiles(struct xfile **abuf, size_t *alen)
416 {
417 	struct xfile *buf;
418 	size_t len;
419 	int mib[2];
420 
421 	/*
422 	 * XXX
423 	 * Add emulation of KINFO_FILE here.
424 	 */
425 	if (kd != NULL)
426 		errx(1, "files on dead kernel, not implemented");
427 
428 	mib[0] = CTL_KERN;
429 	mib[1] = KERN_FILE;
430 	if (sysctl(mib, 2, NULL, &len, NULL, 0) == -1) {
431 		warn("sysctl: KERN_FILE");
432 		return (-1);
433 	}
434 	if ((buf = malloc(len)) == NULL)
435 		errx(1, "malloc");
436 	if (sysctl(mib, 2, buf, &len, NULL, 0) == -1) {
437 		warn("sysctl: KERN_FILE");
438 		return (-1);
439 	}
440 	*abuf = buf;
441 	*alen = len;
442 	return (0);
443 }
444 
445 /*
446  * swapmode is based on a program called swapinfo written
447  * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
448  */
449 
450 #define CONVERT(v)	((int64_t)(v) * pagesize / blocksize)
451 #define CONVERT_BLOCKS(v)	((int64_t)(v) * pagesize)
452 static struct kvm_swap swtot;
453 static int nswdev;
454 
455 static void
456 print_swap_header(void)
457 {
458 	int hlen;
459 	long blocksize;
460 	const char *header;
461 
462 	if (humanflag) {
463 		header = SIZEHDR;
464 		hlen = 8; /* as the hardcoded field width of values */
465 	} else {
466 		header = getbsize(&hlen, &blocksize);
467 	}
468 	if (totalflag == 0)
469 		(void)printf("%-15s %*s %8s %8s %8s\n",
470 		    "Device", hlen, header,
471 		    "Used", "Avail", "Capacity");
472 }
473 
474 static void
475 print_swap_line(const char *swdevname, intmax_t nblks, intmax_t bused,
476     intmax_t bavail, float bpercent)
477 {
478 	char usedbuf[5];
479 	char availbuf[5];
480 	char sizebuf[5];
481 	int hlen, pagesize;
482 	long blocksize;
483 
484 	pagesize = getpagesize();
485 	getbsize(&hlen, &blocksize);
486 
487 	printf("%-15s ", swdevname);
488 	if (humanflag) {
489 		humanize_number(sizebuf, sizeof(sizebuf),
490 		    CONVERT_BLOCKS(nblks), "",
491 		    HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
492 		humanize_number(usedbuf, sizeof(usedbuf),
493 		    CONVERT_BLOCKS(bused), "",
494 		    HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
495 		humanize_number(availbuf, sizeof(availbuf),
496 		    CONVERT_BLOCKS(bavail), "",
497 		    HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
498 		printf("%8s %8s %8s %5.0f%%\n", sizebuf,
499 		    usedbuf, availbuf, bpercent);
500 	} else {
501 		printf("%*jd %8jd %8jd %5.0f%%\n", hlen,
502 		    (intmax_t)CONVERT(nblks),
503 		    (intmax_t)CONVERT(bused),
504 		    (intmax_t)CONVERT(bavail), bpercent);
505 	}
506 }
507 
508 static void
509 print_swap(struct kvm_swap *ksw)
510 {
511 
512 	swtot.ksw_total += ksw->ksw_total;
513 	swtot.ksw_used += ksw->ksw_used;
514 	++nswdev;
515 	if (totalflag == 0)
516 		print_swap_line(ksw->ksw_devname, ksw->ksw_total,
517 		    ksw->ksw_used, ksw->ksw_total - ksw->ksw_used,
518 		    (ksw->ksw_used * 100.0) / ksw->ksw_total);
519 }
520 
521 static void
522 print_swap_total(void)
523 {
524 	int hlen, pagesize;
525 	long blocksize;
526 
527 	pagesize = getpagesize();
528 	getbsize(&hlen, &blocksize);
529 	if (totalflag) {
530 		blocksize = 1024 * 1024;
531 		(void)printf("%jdM/%jdM swap space\n",
532 		    CONVERT(swtot.ksw_used), CONVERT(swtot.ksw_total));
533 	} else if (nswdev > 1) {
534 		print_swap_line("Total", swtot.ksw_total, swtot.ksw_used,
535 		    swtot.ksw_total - swtot.ksw_used,
536 		    (swtot.ksw_used * 100.0) / swtot.ksw_total);
537 	}
538 }
539 
540 static void
541 swapmode_kvm(void)
542 {
543 	struct kvm_swap kswap[16];
544 	int i, n;
545 
546 	n = kvm_getswapinfo(kd, kswap, sizeof kswap / sizeof kswap[0],
547 	    SWIF_DEV_PREFIX);
548 
549 	print_swap_header();
550 	for (i = 0; i < n; ++i)
551 		print_swap(&kswap[i]);
552 	print_swap_total();
553 }
554 
555 static void
556 swapmode_sysctl(void)
557 {
558 	struct kvm_swap ksw;
559 	struct xswdev xsw;
560 	size_t mibsize, size;
561 	int mib[16], n;
562 
563 	print_swap_header();
564 	mibsize = sizeof mib / sizeof mib[0];
565 	if (sysctlnametomib("vm.swap_info", mib, &mibsize) == -1)
566 		err(1, "sysctlnametomib()");
567 	for (n = 0; ; ++n) {
568 		mib[mibsize] = n;
569 		size = sizeof xsw;
570 		if (sysctl(mib, mibsize + 1, &xsw, &size, NULL, 0) == -1)
571 			break;
572 		if (xsw.xsw_version != XSWDEV_VERSION)
573 			errx(1, "xswdev version mismatch");
574 		if (xsw.xsw_dev == NODEV)
575 			snprintf(ksw.ksw_devname, sizeof ksw.ksw_devname,
576 			    "<NFSfile>");
577 		else
578 			snprintf(ksw.ksw_devname, sizeof ksw.ksw_devname,
579 			    "/dev/%s", devname(xsw.xsw_dev, S_IFCHR));
580 		ksw.ksw_used = xsw.xsw_used;
581 		ksw.ksw_total = xsw.xsw_nblks;
582 		ksw.ksw_flags = xsw.xsw_flags;
583 		print_swap(&ksw);
584 	}
585 	if (errno != ENOENT)
586 		err(1, "sysctl()");
587 	print_swap_total();
588 }
589 
590 static void
591 swapmode(void)
592 {
593 	if (kd != NULL)
594 		swapmode_kvm();
595 	else
596 		swapmode_sysctl();
597 }
598