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