xref: /freebsd/usr.sbin/pstat/pstat.c (revision 4f52dfbb)
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 static int	humanflag;
99 static int	usenumflag;
100 static int	totalflag;
101 static int	swapflag;
102 static char	*nlistf;
103 static char	*memf;
104 static kvm_t	*kd;
105 
106 static const char *usagestr;
107 
108 static void	filemode(void);
109 static int	getfiles(struct xfile **, size_t *);
110 static void	swapmode(void);
111 static void	ttymode(void);
112 static void	ttyprt(struct xtty *);
113 static void	usage(void);
114 
115 int
116 main(int argc, char *argv[])
117 {
118 	int ch, quit, ret;
119 	int fileflag, ttyflag;
120 	unsigned int i;
121 	char buf[_POSIX2_LINE_MAX];
122 	const char *opts;
123 
124 	fileflag = swapflag = ttyflag = 0;
125 
126 	/* We will behave like good old swapinfo if thus invoked */
127 	opts = strrchr(argv[0], '/');
128 	if (opts)
129 		opts++;
130 	else
131 		opts = argv[0];
132 	if (!strcmp(opts, "swapinfo")) {
133 		swapflag = 1;
134 		opts = "ghkmM:N:";
135 		usagestr = "swapinfo [-ghkm] [-M core [-N system]]";
136 	} else {
137 		opts = "TM:N:fghkmnst";
138 		usagestr = "pstat [-Tfghkmnst] [-M core [-N system]]";
139 	}
140 
141 	while ((ch = getopt(argc, argv, opts)) != -1)
142 		switch (ch) {
143 		case 'f':
144 			fileflag = 1;
145 			break;
146 		case 'g':
147 			setenv("BLOCKSIZE", "1G", 1);
148 			break;
149 		case 'h':
150 			humanflag = 1;
151 			break;
152 		case 'k':
153 			setenv("BLOCKSIZE", "1K", 1);
154 			break;
155 		case 'm':
156 			setenv("BLOCKSIZE", "1M", 1);
157 			break;
158 		case 'M':
159 			memf = optarg;
160 			break;
161 		case 'N':
162 			nlistf = optarg;
163 			break;
164 		case 'n':
165 			usenumflag = 1;
166 			break;
167 		case 's':
168 			++swapflag;
169 			break;
170 		case 'T':
171 			totalflag = 1;
172 			break;
173 		case 't':
174 			ttyflag = 1;
175 			break;
176 		default:
177 			usage();
178 		}
179 
180 	/*
181 	 * Initialize symbol names list.
182 	 */
183 	for (i = 0; i < NNAMES; i++)
184 		nl[namelist[i].order].n_name = strdup(namelist[i].name);
185 
186 	if (memf != NULL) {
187 		kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, buf);
188 		if (kd == NULL)
189 			errx(1, "kvm_openfiles: %s", buf);
190 		if ((ret = kvm_nlist(kd, nl)) != 0) {
191 			if (ret == -1)
192 				errx(1, "kvm_nlist: %s", kvm_geterr(kd));
193 			quit = 0;
194 			for (i = 0; nl[i].n_name[0] != '\0'; ++i)
195 				if (nl[i].n_value == 0) {
196 					quit = 1;
197 					warnx("undefined symbol: %s",
198 					    nl[i].n_name);
199 				}
200 			if (quit)
201 				exit(1);
202 		}
203 	}
204 	if (!(fileflag | ttyflag | swapflag | totalflag))
205 		usage();
206 	if (fileflag || totalflag)
207 		filemode();
208 	if (ttyflag)
209 		ttymode();
210 	if (swapflag || totalflag)
211 		swapmode();
212 	exit (0);
213 }
214 
215 static void
216 usage(void)
217 {
218 	fprintf(stderr, "usage: %s\n", usagestr);
219 	exit (1);
220 }
221 
222 static const char fhdr32[] =
223   "   LOC   TYPE   FLG  CNT MSG   DATA        OFFSET\n";
224 /* c0000000 ------ RWAI 123 123 c0000000 1000000000000000 */
225 
226 static const char fhdr64[] =
227   "       LOC       TYPE   FLG  CNT MSG       DATA            OFFSET\n";
228 /* c000000000000000 ------ RWAI 123 123 c000000000000000 1000000000000000 */
229 
230 static const char hdr[] =
231 "      LINE   INQ  CAN  LIN  LOW  OUTQ  USE  LOW   COL  SESS  PGID STATE\n";
232 
233 static void
234 ttymode_kvm(void)
235 {
236 	TAILQ_HEAD(, tty) tl;
237 	struct tty *tp, tty;
238 	struct xtty xt;
239 
240 	(void)printf("%s", hdr);
241 	bzero(&xt, sizeof xt);
242 	xt.xt_size = sizeof xt;
243 	if (kvm_read(kd, nl[NL_TTY_LIST].n_value, &tl, sizeof tl) != sizeof tl)
244 		errx(1, "kvm_read(): %s", kvm_geterr(kd));
245 	tp = TAILQ_FIRST(&tl);
246 	while (tp != NULL) {
247 		if (kvm_read(kd, (u_long)tp, &tty, sizeof tty) != sizeof tty)
248 			errx(1, "kvm_read(): %s", kvm_geterr(kd));
249 		xt.xt_insize = tty.t_inq.ti_nblocks * TTYINQ_DATASIZE;
250 		xt.xt_incc = tty.t_inq.ti_linestart - tty.t_inq.ti_begin;
251 		xt.xt_inlc = tty.t_inq.ti_end - tty.t_inq.ti_linestart;
252 		xt.xt_inlow = tty.t_inlow;
253 		xt.xt_outsize = tty.t_outq.to_nblocks * TTYOUTQ_DATASIZE;
254 		xt.xt_outcc = tty.t_outq.to_end - tty.t_outq.to_begin;
255 		xt.xt_outlow = tty.t_outlow;
256 		xt.xt_column = tty.t_column;
257 		/* xt.xt_pgid = ... */
258 		/* xt.xt_sid = ... */
259 		xt.xt_flags = tty.t_flags;
260 		xt.xt_dev = (uint32_t)NODEV;
261 		ttyprt(&xt);
262 		tp = TAILQ_NEXT(&tty, t_list);
263 	}
264 }
265 
266 static void
267 ttymode_sysctl(void)
268 {
269 	struct xtty *xttys;
270 	size_t len;
271 	unsigned int i, n;
272 
273 	(void)printf("%s", hdr);
274 	if ((xttys = malloc(len = sizeof(*xttys))) == NULL)
275 		err(1, "malloc()");
276 	while (sysctlbyname("kern.ttys", xttys, &len, 0, 0) == -1) {
277 		if (errno != ENOMEM)
278 			err(1, "sysctlbyname()");
279 		len *= 2;
280 		if ((xttys = realloc(xttys, len)) == NULL)
281 			err(1, "realloc()");
282 	}
283 	n = len / sizeof(*xttys);
284 	for (i = 0; i < n; i++)
285 		ttyprt(&xttys[i]);
286 }
287 
288 static void
289 ttymode(void)
290 {
291 
292 	if (kd != NULL)
293 		ttymode_kvm();
294 	else
295 		ttymode_sysctl();
296 }
297 
298 static struct {
299 	int flag;
300 	char val;
301 } ttystates[] = {
302 #if 0
303 	{ TF_NOPREFIX,		'N' },
304 #endif
305 	{ TF_INITLOCK,		'I' },
306 	{ TF_CALLOUT,		'C' },
307 
308 	/* Keep these together -> 'Oi' and 'Oo'. */
309 	{ TF_OPENED,		'O' },
310 	{ TF_OPENED_IN,		'i' },
311 	{ TF_OPENED_OUT,	'o' },
312 	{ TF_OPENED_CONS,	'c' },
313 
314 	{ TF_GONE,		'G' },
315 	{ TF_OPENCLOSE,		'B' },
316 	{ TF_ASYNC,		'Y' },
317 	{ TF_LITERAL,		'L' },
318 
319 	/* Keep these together -> 'Hi' and 'Ho'. */
320 	{ TF_HIWAT,		'H' },
321 	{ TF_HIWAT_IN,		'i' },
322 	{ TF_HIWAT_OUT,		'o' },
323 
324 	{ TF_STOPPED,		'S' },
325 	{ TF_EXCLUDE,		'X' },
326 	{ TF_BYPASS,		'l' },
327 	{ TF_ZOMBIE,		'Z' },
328 	{ TF_HOOK,		's' },
329 
330 	/* Keep these together -> 'bi' and 'bo'. */
331 	{ TF_BUSY,		'b' },
332 	{ TF_BUSY_IN,		'i' },
333 	{ TF_BUSY_OUT,		'o' },
334 
335 	{ 0,			'\0'},
336 };
337 
338 static void
339 ttyprt(struct xtty *xt)
340 {
341 	int i, j;
342 	const char *name;
343 
344 	if (xt->xt_size != sizeof *xt)
345 		errx(1, "struct xtty size mismatch");
346 	if (usenumflag || xt->xt_dev == 0 ||
347 	   (name = devname(xt->xt_dev, S_IFCHR)) == NULL)
348 		printf("%#10jx ", (uintmax_t)xt->xt_dev);
349 	else
350 		printf("%10s ", name);
351 	printf("%5zu %4zu %4zu %4zu %5zu %4zu %4zu %5u %5d %5d ",
352 	    xt->xt_insize, xt->xt_incc, xt->xt_inlc,
353 	    (xt->xt_insize - xt->xt_inlow), xt->xt_outsize,
354 	    xt->xt_outcc, (xt->xt_outsize - xt->xt_outlow),
355 	    MIN(xt->xt_column, 99999), xt->xt_sid, xt->xt_pgid);
356 	for (i = j = 0; ttystates[i].flag; i++)
357 		if (xt->xt_flags & ttystates[i].flag) {
358 			putchar(ttystates[i].val);
359 			j++;
360 		}
361 	if (j == 0)
362 		putchar('-');
363 	putchar('\n');
364 }
365 
366 static void
367 filemode(void)
368 {
369 	struct xfile *fp, *buf;
370 	char flagbuf[16], *fbp;
371 	int maxf, openf;
372 	size_t len;
373 	static char const * const dtypes[] = { "???", "inode", "socket",
374 	    "pipe", "fifo", "kqueue", "crypto" };
375 	int i;
376 	int wid;
377 
378 	if (kd != NULL) {
379 		if (kvm_read(kd, nl[NL_MAXFILES].n_value,
380 			&maxf, sizeof maxf) != sizeof maxf ||
381 		    kvm_read(kd, nl[NL_NFILES].n_value,
382 			&openf, sizeof openf) != sizeof openf)
383 			errx(1, "kvm_read(): %s", kvm_geterr(kd));
384 	} else {
385 		len = sizeof(int);
386 		if (sysctlbyname("kern.maxfiles", &maxf, &len, 0, 0) == -1 ||
387 		    sysctlbyname("kern.openfiles", &openf, &len, 0, 0) == -1)
388 			err(1, "sysctlbyname()");
389 	}
390 
391 	if (totalflag) {
392 		(void)printf("%3d/%3d files\n", openf, maxf);
393 		return;
394 	}
395 	if (getfiles(&buf, &len) == -1)
396 		return;
397 	openf = len / sizeof *fp;
398 
399 	(void)printf("%d/%d open files\n", openf, maxf);
400 	printf(sizeof(uintptr_t) == 4 ? fhdr32 : fhdr64);
401 	wid = (int)sizeof(uintptr_t) * 2;
402 	for (fp = (struct xfile *)buf, i = 0; i < openf; ++fp, ++i) {
403 		if ((size_t)fp->xf_type >= sizeof(dtypes) / sizeof(dtypes[0]))
404 			continue;
405 		(void)printf("%*jx", wid, (uintmax_t)(uintptr_t)fp->xf_file);
406 		(void)printf(" %-6.6s", dtypes[fp->xf_type]);
407 		fbp = flagbuf;
408 		if (fp->xf_flag & FREAD)
409 			*fbp++ = 'R';
410 		if (fp->xf_flag & FWRITE)
411 			*fbp++ = 'W';
412 		if (fp->xf_flag & FAPPEND)
413 			*fbp++ = 'A';
414 		if (fp->xf_flag & FASYNC)
415 			*fbp++ = 'I';
416 		*fbp = '\0';
417 		(void)printf(" %4s %3d", flagbuf, fp->xf_count);
418 		(void)printf(" %3d", fp->xf_msgcount);
419 		(void)printf(" %*jx", wid, (uintmax_t)(uintptr_t)fp->xf_data);
420 		(void)printf(" %*jx\n", (int)sizeof(fp->xf_offset) * 2,
421 		    (uintmax_t)fp->xf_offset);
422 	}
423 	free(buf);
424 }
425 
426 static int
427 getfiles(struct xfile **abuf, size_t *alen)
428 {
429 	struct xfile *buf;
430 	size_t len;
431 	int mib[2];
432 
433 	/*
434 	 * XXX
435 	 * Add emulation of KINFO_FILE here.
436 	 */
437 	if (kd != NULL)
438 		errx(1, "files on dead kernel, not implemented");
439 
440 	mib[0] = CTL_KERN;
441 	mib[1] = KERN_FILE;
442 	if (sysctl(mib, 2, NULL, &len, NULL, 0) == -1) {
443 		warn("sysctl: KERN_FILE");
444 		return (-1);
445 	}
446 	if ((buf = malloc(len)) == NULL)
447 		errx(1, "malloc");
448 	if (sysctl(mib, 2, buf, &len, NULL, 0) == -1) {
449 		warn("sysctl: KERN_FILE");
450 		return (-1);
451 	}
452 	*abuf = buf;
453 	*alen = len;
454 	return (0);
455 }
456 
457 /*
458  * swapmode is based on a program called swapinfo written
459  * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
460  */
461 
462 #define CONVERT(v)	((int64_t)(v) * pagesize / blocksize)
463 #define CONVERT_BLOCKS(v)	((int64_t)(v) * pagesize)
464 static struct kvm_swap swtot;
465 static int nswdev;
466 
467 static void
468 print_swap_header(void)
469 {
470 	int hlen;
471 	long blocksize;
472 	const char *header;
473 
474 	header = getbsize(&hlen, &blocksize);
475 	if (totalflag == 0)
476 		(void)printf("%-15s %*s %8s %8s %8s\n",
477 		    "Device", hlen, header,
478 		    "Used", "Avail", "Capacity");
479 }
480 
481 static void
482 print_swap_line(const char *swdevname, intmax_t nblks, intmax_t bused,
483     intmax_t bavail, float bpercent)
484 {
485 	char usedbuf[5];
486 	char availbuf[5];
487 	int hlen, pagesize;
488 	long blocksize;
489 
490 	pagesize = getpagesize();
491 	getbsize(&hlen, &blocksize);
492 
493 	printf("%-15s %*jd ", swdevname, hlen, CONVERT(nblks));
494 	if (humanflag) {
495 		humanize_number(usedbuf, sizeof(usedbuf),
496 		    CONVERT_BLOCKS(bused), "",
497 		    HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
498 		humanize_number(availbuf, sizeof(availbuf),
499 		    CONVERT_BLOCKS(bavail), "",
500 		    HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
501 		printf("%8s %8s %5.0f%%\n", usedbuf, availbuf, bpercent);
502 	} else {
503 		printf("%8jd %8jd %5.0f%%\n", (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