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