xref: /freebsd/usr.sbin/pstat/pstat.c (revision cacdd70cc751fb68dec4b86c5e5b8c969b6e26ef)
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 RAW CAN OUT IHIWT ILOWT OHWT LWT     COL STATE  SESS      PGID DISC\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_rawcc = tty.t_rawq.c_cc;
236 		xt.xt_cancc = tty.t_canq.c_cc;
237 		xt.xt_outcc = tty.t_outq.c_cc;
238 #define XT_COPY(field) xt.xt_##field = tty.t_##field
239 		XT_COPY(line);
240 		XT_COPY(state);
241 		XT_COPY(column);
242 		XT_COPY(ihiwat);
243 		XT_COPY(ilowat);
244 		XT_COPY(ohiwat);
245 		XT_COPY(olowat);
246 #undef XT_COPY
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 #ifdef TS_WOPEN
291 	{ TS_WOPEN,	'W'},
292 #endif
293 	{ TS_ISOPEN,	'O'},
294 	{ TS_CARR_ON,	'C'},
295 #ifdef TS_CONNECTED
296 	{ TS_CONNECTED,	'c'},
297 #endif
298 	{ TS_TIMEOUT,	'T'},
299 	{ TS_FLUSH,	'F'},
300 	{ TS_BUSY,	'B'},
301 #ifdef TS_ASLEEP
302 	{ TS_ASLEEP,	'A'},
303 #endif
304 #ifdef TS_SO_OLOWAT
305 	{ TS_SO_OLOWAT,	'A'},
306 #endif
307 #ifdef TS_SO_OCOMPLETE
308 	{ TS_SO_OCOMPLETE, 'a'},
309 #endif
310 	{ TS_XCLUDE,	'X'},
311 	{ TS_TTSTOP,	'S'},
312 #ifdef TS_CAR_OFLOW
313 	{ TS_CAR_OFLOW,	'm'},
314 #endif
315 #ifdef TS_CTS_OFLOW
316 	{ TS_CTS_OFLOW,	'o'},
317 #endif
318 #ifdef TS_DSR_OFLOW
319 	{ TS_DSR_OFLOW,	'd'},
320 #endif
321 	{ TS_TBLOCK,	'K'},
322 	{ TS_ASYNC,	'Y'},
323 	{ TS_BKSL,	'D'},
324 	{ TS_ERASE,	'E'},
325 	{ TS_LNCH,	'L'},
326 	{ TS_TYPEN,	'P'},
327 	{ TS_CNTTB,	'N'},
328 #ifdef TS_CAN_BYPASS_L_RINT
329 	{ TS_CAN_BYPASS_L_RINT, 'l'},
330 #endif
331 #ifdef TS_SNOOP
332 	{ TS_SNOOP,     's'},
333 #endif
334 #ifdef TS_ZOMBIE
335 	{ TS_ZOMBIE,	'Z'},
336 #endif
337 	{ 0,	       '\0'},
338 };
339 
340 static void
341 ttyprt(struct xtty *xt)
342 {
343 	int i, j;
344 	char *name, state[20];
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("   %2d,%-2d", major(xt->xt_dev), minor(xt->xt_dev));
351 	else
352 		(void)printf("%7s ", name);
353 	(void)printf("%2ld %3ld ", xt->xt_rawcc, xt->xt_cancc);
354 	(void)printf("%3ld %5d %5d %4d %3d %7d ", xt->xt_outcc,
355 		xt->xt_ihiwat, xt->xt_ilowat, xt->xt_ohiwat, xt->xt_olowat,
356 		xt->xt_column);
357 	for (i = j = 0; ttystates[i].flag; i++)
358 		if (xt->xt_state & ttystates[i].flag)
359 			state[j++] = ttystates[i].val;
360 	if (j == 0)
361 		state[j++] = '-';
362 	state[j] = '\0';
363 	(void)printf("%-6s %8d", state, xt->xt_sid);
364 	(void)printf("%6d ", xt->xt_pgid);
365 	switch (xt->xt_line) {
366 	case TTYDISC:
367 		(void)printf("term\n");
368 		break;
369 	case SLIPDISC:
370 		(void)printf("slip\n");
371 		break;
372 	case PPPDISC:
373 		(void)printf("ppp\n");
374 		break;
375 	default:
376 		(void)printf("%d\n", xt->xt_line);
377 		break;
378 	}
379 }
380 
381 static void
382 filemode(void)
383 {
384 	struct xfile *fp;
385 	char *buf, flagbuf[16], *fbp;
386 	int maxf, openf;
387 	size_t len;
388 	static char *dtypes[] = { "???", "inode", "socket", "pipe",
389 	    "fifo", "kqueue", "crypto" };
390 	int i;
391 	int wid;
392 
393 	if (kd != NULL) {
394 		if (kvm_read(kd, nl[NL_MAXFILES].n_value,
395 			&maxf, sizeof maxf) != sizeof maxf ||
396 		    kvm_read(kd, nl[NL_NFILES].n_value,
397 			&openf, sizeof openf) != sizeof openf)
398 			errx(1, "kvm_read(): %s", kvm_geterr(kd));
399 	} else {
400 		len = sizeof(int);
401 		if (sysctlbyname("kern.maxfiles", &maxf, &len, 0, 0) == -1 ||
402 		    sysctlbyname("kern.openfiles", &openf, &len, 0, 0) == -1)
403 			err(1, "sysctlbyname()");
404 	}
405 
406 	if (totalflag) {
407 		(void)printf("%3d/%3d files\n", openf, maxf);
408 		return;
409 	}
410 	if (getfiles(&buf, &len) == -1)
411 		return;
412 	openf = len / sizeof *fp;
413 
414 	(void)printf("%d/%d open files\n", openf, maxf);
415 	printf(sizeof(uintptr_t) == 4 ? fhdr32 : fhdr64);
416 	wid = (int)sizeof(uintptr_t) * 2;
417 	for (fp = (struct xfile *)buf, i = 0; i < openf; ++fp, ++i) {
418 		if ((size_t)fp->xf_type >= sizeof(dtypes) / sizeof(dtypes[0]))
419 			continue;
420 		(void)printf("%*jx", wid, (uintmax_t)(uintptr_t)fp->xf_file);
421 		(void)printf(" %-6.6s", dtypes[fp->xf_type]);
422 		fbp = flagbuf;
423 		if (fp->xf_flag & FREAD)
424 			*fbp++ = 'R';
425 		if (fp->xf_flag & FWRITE)
426 			*fbp++ = 'W';
427 		if (fp->xf_flag & FAPPEND)
428 			*fbp++ = 'A';
429 		if (fp->xf_flag & FASYNC)
430 			*fbp++ = 'I';
431 		*fbp = '\0';
432 		(void)printf(" %4s %3d", flagbuf, fp->xf_count);
433 		(void)printf(" %3d", fp->xf_msgcount);
434 		(void)printf(" %*jx", wid, (uintmax_t)(uintptr_t)fp->xf_data);
435 		(void)printf(" %*jx\n", (int)sizeof(fp->xf_offset) * 2,
436 		    (uintmax_t)fp->xf_offset);
437 	}
438 	free(buf);
439 }
440 
441 static int
442 getfiles(char **abuf, size_t *alen)
443 {
444 	size_t len;
445 	int mib[2];
446 	char *buf;
447 
448 	/*
449 	 * XXX
450 	 * Add emulation of KINFO_FILE here.
451 	 */
452 	if (kd != NULL)
453 		errx(1, "files on dead kernel, not implemented");
454 
455 	mib[0] = CTL_KERN;
456 	mib[1] = KERN_FILE;
457 	if (sysctl(mib, 2, NULL, &len, NULL, 0) == -1) {
458 		warn("sysctl: KERN_FILE");
459 		return (-1);
460 	}
461 	if ((buf = malloc(len)) == NULL)
462 		errx(1, "malloc");
463 	if (sysctl(mib, 2, buf, &len, NULL, 0) == -1) {
464 		warn("sysctl: KERN_FILE");
465 		return (-1);
466 	}
467 	*abuf = buf;
468 	*alen = len;
469 	return (0);
470 }
471 
472 /*
473  * swapmode is based on a program called swapinfo written
474  * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
475  */
476 
477 #define CONVERT(v)	((int64_t)(v) * pagesize / blocksize)
478 static struct kvm_swap swtot;
479 static int nswdev;
480 
481 static void
482 print_swap_header(void)
483 {
484 	int hlen;
485 	long blocksize;
486 	const char *header;
487 
488 	header = getbsize(&hlen, &blocksize);
489 	if (totalflag == 0)
490 		(void)printf("%-15s %*s %8s %8s %8s\n",
491 		    "Device", hlen, header,
492 		    "Used", "Avail", "Capacity");
493 }
494 
495 static void
496 print_swap_line(const char *devname, intmax_t nblks, intmax_t bused,
497     intmax_t bavail, float bpercent)
498 {
499 	char usedbuf[5];
500 	char availbuf[5];
501 	int hlen, pagesize;
502 	long blocksize;
503 
504 	pagesize = getpagesize();
505 	getbsize(&hlen, &blocksize);
506 
507 	printf("%-15s %*jd ", devname, hlen, CONVERT(nblks));
508 	if (humanflag) {
509 		humanize_number(usedbuf, sizeof(usedbuf),
510 		    CONVERT(blocksize * bused), "",
511 		    HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
512 		humanize_number(availbuf, sizeof(availbuf),
513 		    CONVERT(blocksize * bavail), "",
514 		    HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
515 		printf("%8s %8s %5.0f%%\n", usedbuf, availbuf, bpercent);
516 	} else {
517 		printf("%8jd %8jd %5.0f%%\n", (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