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