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