pstat.c revision 114601
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 * 3. All advertising materials mentioning features or use of this software
21 *    must display the following acknowledgement:
22 *	This product includes software developed by the University of
23 *	California, Berkeley and its contributors.
24 * 4. Neither the name of the University nor the names of its contributors
25 *    may be used to endorse or promote products derived from this software
26 *    without specific prior written permission.
27 *
28 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * SUCH DAMAGE.
39 */
40
41#if 0
42#ifndef lint
43static const char copyright[] =
44"@(#) Copyright (c) 1980, 1991, 1993, 1994\n\
45	The Regents of the University of California.  All rights reserved.\n";
46#endif /* not lint */
47
48#ifndef lint
49static char sccsid[] = "@(#)pstat.c	8.16 (Berkeley) 5/9/95";
50#endif /* not lint */
51#endif
52#include <sys/cdefs.h>
53__FBSDID("$FreeBSD: head/usr.sbin/pstat/pstat.c 114601 2003-05-03 21:06:42Z obrien $");
54
55#include <sys/param.h>
56#include <sys/time.h>
57#include <sys/file.h>
58#include <sys/stat.h>
59#include <sys/stdint.h>
60#include <sys/ioctl.h>
61#include <sys/ioctl_compat.h>	/* XXX NTTYDISC is too well hidden */
62#include <sys/tty.h>
63#include <sys/blist.h>
64
65#include <sys/user.h>
66#include <sys/sysctl.h>
67#include <vm/swap_pager.h>
68
69#include <err.h>
70#include <fcntl.h>
71#include <kvm.h>
72#include <limits.h>
73#include <nlist.h>
74#include <stdio.h>
75#include <stdlib.h>
76#include <string.h>
77#include <unistd.h>
78
79enum {
80	NL_CONSTTY,
81	NL_MAXFILES,
82	NL_NFILES,
83	NL_TTY_LIST
84};
85
86static struct nlist nl[] = {
87	{ "_constty", 0 },
88	{ "_maxfiles", 0 },
89	{ "_nfiles", 0 },
90	{ "_tty_list", 0 },
91	{ "" }
92};
93
94static int	usenumflag;
95static int	totalflag;
96static int	swapflag;
97static char	*nlistf;
98static char	*memf;
99static kvm_t	*kd;
100
101static char	*usagestr;
102
103static void	filemode(void);
104static int	getfiles(char **, size_t *);
105static void	swapmode(void);
106static void	ttymode(void);
107static void	ttyprt(struct xtty *);
108static void	usage(void);
109
110int
111main(int argc, char *argv[])
112{
113	int ch, i, quit, ret;
114	int fileflag, ttyflag;
115	char buf[_POSIX2_LINE_MAX],*opts;
116
117	fileflag = swapflag = ttyflag = 0;
118
119	/* We will behave like good old swapinfo if thus invoked */
120	opts = strrchr(argv[0], '/');
121	if (opts)
122		opts++;
123	else
124		opts = argv[0];
125	if (!strcmp(opts, "swapinfo")) {
126		swapflag = 1;
127		opts = "kM:N:";
128		usagestr = "swapinfo [-k] [-M core] [-N system]";
129	} else {
130		opts = "TM:N:fknst";
131		usagestr = "pstat [-Tfknst] [-M core] [-N system]";
132	}
133
134	while ((ch = getopt(argc, argv, opts)) != -1)
135		switch (ch) {
136		case 'f':
137			fileflag = 1;
138			break;
139		case 'k':
140			putenv("BLOCKSIZE=1K");
141			break;
142		case 'M':
143			memf = optarg;
144			break;
145		case 'N':
146			nlistf = optarg;
147			break;
148		case 'n':
149			usenumflag = 1;
150			break;
151		case 's':
152			++swapflag;
153			break;
154		case 'T':
155			totalflag = 1;
156			break;
157		case 't':
158			ttyflag = 1;
159			break;
160		default:
161			usage();
162		}
163	argc -= optind;
164	argv += optind;
165
166	if (memf != NULL) {
167		kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, buf);
168		if (kd == NULL)
169			errx(1, "kvm_openfiles: %s", buf);
170		if ((ret = kvm_nlist(kd, nl)) != 0) {
171			if (ret == -1)
172				errx(1, "kvm_nlist: %s", kvm_geterr(kd));
173			quit = 0;
174			for (i = 0; nl[i].n_name[0] != '\0'; ++i)
175				if (nl[i].n_value == 0) {
176					quit = 1;
177					warnx("undefined symbol: %s",
178					    nl[i].n_name);
179				}
180			if (quit)
181				exit(1);
182		}
183	}
184	if (!(fileflag | ttyflag | swapflag | totalflag))
185		usage();
186	if (fileflag || totalflag)
187		filemode();
188	if (ttyflag)
189		ttymode();
190	if (swapflag || totalflag)
191		swapmode();
192	exit (0);
193}
194
195static void
196usage(void)
197{
198	fprintf(stderr, "usage: %s\n", usagestr);
199	exit (1);
200}
201
202static const char fhdr32[] =
203  "   LOC   TYPE   FLG  CNT MSG   DATA        OFFSET\n";
204/* c0000000 ------ RWAI 123 123 c0000000 1000000000000000 */
205
206static const char fhdr64[] =
207  "       LOC       TYPE   FLG  CNT MSG       DATA            OFFSET\n";
208/* c000000000000000 ------ RWAI 123 123 c000000000000000 1000000000000000 */
209
210static const char hdr[] =
211"  LINE RAW CAN OUT IHIWT ILOWT OHWT LWT     COL STATE  SESS      PGID DISC\n";
212
213static void
214ttymode_kvm(void)
215{
216	SLIST_HEAD(, tty) tl;
217	struct tty *tp, tty;
218	struct xtty xt;
219
220	(void)printf("%s", hdr);
221	bzero(&xt, sizeof xt);
222	xt.xt_size = sizeof xt;
223	if (kvm_read(kd, nl[NL_TTY_LIST].n_value, &tl, sizeof tl) != sizeof tl)
224		errx(1, "kvm_read(): %s", kvm_geterr(kd));
225	tp = SLIST_FIRST(&tl);
226	while (tp != NULL) {
227		if (kvm_read(kd, (u_long)tp, &tty, sizeof tty) != sizeof tty)
228			errx(1, "kvm_read(): %s", kvm_geterr(kd));
229		xt.xt_rawcc = tty.t_rawq.c_cc;
230		xt.xt_cancc = tty.t_canq.c_cc;
231		xt.xt_outcc = tty.t_outq.c_cc;
232#define XT_COPY(field) xt.xt_##field = tty.t_##field
233		XT_COPY(line);
234		XT_COPY(state);
235		XT_COPY(column);
236		XT_COPY(ihiwat);
237		XT_COPY(ilowat);
238		XT_COPY(ohiwat);
239		XT_COPY(olowat);
240#undef XT_COPY
241		ttyprt(&xt);
242		tp = tty.t_list.sle_next;
243	}
244}
245
246static void
247ttymode_sysctl(void)
248{
249	struct xtty *xt, *end;
250	void *xttys;
251	size_t len;
252
253	(void)printf("%s", hdr);
254	if ((xttys = malloc(len = sizeof *xt)) == NULL)
255		err(1, "malloc()");
256	while (sysctlbyname("kern.ttys", xttys, &len, 0, 0) == -1) {
257		if (errno != ENOMEM)
258			err(1, "sysctlbyname()");
259		len *= 2;
260		if ((xttys = realloc(xttys, len)) == NULL)
261			err(1, "realloc()");
262	}
263	if (len > 0) {
264		end = (struct xtty *)((char *)xttys + len);
265		for (xt = xttys; xt < end; xt++)
266			ttyprt(xt);
267	}
268}
269
270static void
271ttymode(void)
272{
273
274	if (kd != NULL)
275		ttymode_kvm();
276	else
277		ttymode_sysctl();
278}
279
280static struct {
281	int flag;
282	char val;
283} ttystates[] = {
284#ifdef TS_WOPEN
285	{ TS_WOPEN,	'W'},
286#endif
287	{ TS_ISOPEN,	'O'},
288	{ TS_CARR_ON,	'C'},
289#ifdef TS_CONNECTED
290	{ TS_CONNECTED,	'c'},
291#endif
292	{ TS_TIMEOUT,	'T'},
293	{ TS_FLUSH,	'F'},
294	{ TS_BUSY,	'B'},
295#ifdef TS_ASLEEP
296	{ TS_ASLEEP,	'A'},
297#endif
298#ifdef TS_SO_OLOWAT
299	{ TS_SO_OLOWAT,	'A'},
300#endif
301#ifdef TS_SO_OCOMPLETE
302	{ TS_SO_OCOMPLETE, 'a'},
303#endif
304	{ TS_XCLUDE,	'X'},
305	{ TS_TTSTOP,	'S'},
306#ifdef TS_CAR_OFLOW
307	{ TS_CAR_OFLOW,	'm'},
308#endif
309#ifdef TS_CTS_OFLOW
310	{ TS_CTS_OFLOW,	'o'},
311#endif
312#ifdef TS_DSR_OFLOW
313	{ TS_DSR_OFLOW,	'd'},
314#endif
315	{ TS_TBLOCK,	'K'},
316	{ TS_ASYNC,	'Y'},
317	{ TS_BKSL,	'D'},
318	{ TS_ERASE,	'E'},
319	{ TS_LNCH,	'L'},
320	{ TS_TYPEN,	'P'},
321	{ TS_CNTTB,	'N'},
322#ifdef TS_CAN_BYPASS_L_RINT
323	{ TS_CAN_BYPASS_L_RINT, 'l'},
324#endif
325#ifdef TS_SNOOP
326	{ TS_SNOOP,     's'},
327#endif
328#ifdef TS_ZOMBIE
329	{ TS_ZOMBIE,	'Z'},
330#endif
331	{ 0,	       '\0'},
332};
333
334static void
335ttyprt(struct xtty *xt)
336{
337	int i, j;
338	pid_t pgid;
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	pgid = 0;
360	(void)printf("%6d ", xt->xt_pgid);
361	switch (xt->xt_line) {
362	case TTYDISC:
363		(void)printf("term\n");
364		break;
365	case NTTYDISC:
366		(void)printf("ntty\n");
367		break;
368	case SLIPDISC:
369		(void)printf("slip\n");
370		break;
371	case PPPDISC:
372		(void)printf("ppp\n");
373		break;
374	default:
375		(void)printf("%d\n", xt->xt_line);
376		break;
377	}
378}
379
380static void
381filemode(void)
382{
383	struct xfile *fp;
384	char *buf, flagbuf[16], *fbp;
385	int maxf, openf;
386	size_t len;
387	static char *dtypes[] = { "???", "inode", "socket", "pipe",
388	    "fifo", "kqueue", "crypto" };
389	int i;
390	int wid;
391
392	if (kd != NULL) {
393		if (kvm_read(kd, nl[NL_MAXFILES].n_value,
394			&maxf, sizeof maxf) != sizeof maxf ||
395		    kvm_read(kd, nl[NL_NFILES].n_value,
396			&openf, sizeof openf) != sizeof openf)
397			errx(1, "kvm_read(): %s", kvm_geterr(kd));
398	} else {
399		len = sizeof(int);
400		if (sysctlbyname("kern.maxfiles", &maxf, &len, 0, 0) == -1 ||
401		    sysctlbyname("kern.openfiles", &openf, &len, 0, 0) == -1)
402			err(1, "sysctlbyname()");
403	}
404
405	if (totalflag) {
406		(void)printf("%3d/%3d files\n", openf, maxf);
407		return;
408	}
409	if (getfiles(&buf, &len) == -1)
410		return;
411	openf = len / sizeof *fp;
412
413	(void)printf("%d/%d open files\n", openf, maxf);
414	printf(sizeof(uintptr_t) == 4 ? fhdr32 : fhdr64);
415	wid = (int)sizeof(uintptr_t) * 2;
416	for (fp = (struct xfile *)buf, i = 0; i < openf; ++fp, ++i) {
417		if ((size_t)fp->xf_type >= sizeof(dtypes) / sizeof(dtypes[0]))
418			continue;
419		(void)printf("%*jx", wid, (uintmax_t)(uintptr_t)fp->xf_file);
420		(void)printf(" %-6.6s", dtypes[fp->xf_type]);
421		fbp = flagbuf;
422		if (fp->xf_flag & FREAD)
423			*fbp++ = 'R';
424		if (fp->xf_flag & FWRITE)
425			*fbp++ = 'W';
426		if (fp->xf_flag & FAPPEND)
427			*fbp++ = 'A';
428		if (fp->xf_flag & FASYNC)
429			*fbp++ = 'I';
430		*fbp = '\0';
431		(void)printf(" %4s %3d", flagbuf, fp->xf_count);
432		(void)printf(" %3d", fp->xf_msgcount);
433		(void)printf(" %*jx", wid, (uintmax_t)(uintptr_t)fp->xf_data);
434		(void)printf(" %*jx\n", (int)sizeof(fp->xf_offset) * 2,
435		    (uintmax_t)fp->xf_offset);
436	}
437	free(buf);
438}
439
440static int
441getfiles(char **abuf, size_t *alen)
442{
443	size_t len;
444	int mib[2];
445	char *buf;
446
447	/*
448	 * XXX
449	 * Add emulation of KINFO_FILE here.
450	 */
451	if (kd != NULL)
452		errx(1, "files on dead kernel, not implemented");
453
454	mib[0] = CTL_KERN;
455	mib[1] = KERN_FILE;
456	if (sysctl(mib, 2, NULL, &len, NULL, 0) == -1) {
457		warn("sysctl: KERN_FILE");
458		return (-1);
459	}
460	if ((buf = malloc(len)) == NULL)
461		errx(1, "malloc");
462	if (sysctl(mib, 2, buf, &len, NULL, 0) == -1) {
463		warn("sysctl: KERN_FILE");
464		return (-1);
465	}
466	*abuf = buf;
467	*alen = len;
468	return (0);
469}
470
471/*
472 * swapmode is based on a program called swapinfo written
473 * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
474 */
475
476#define CONVERT(v)	((int)((intmax_t)(v) * pagesize / blocksize))
477static struct kvm_swap swtot;
478static int nswdev;
479
480static void
481print_swap_header(void)
482{
483	int hlen;
484	long blocksize;
485	const char *header;
486
487	header = getbsize(&hlen, &blocksize);
488	if (totalflag == 0)
489		(void)printf("%-15s %*s %8s %8s %8s  %s\n",
490		    "Device", hlen, header,
491		    "Used", "Avail", "Capacity", "Type");
492}
493
494static void
495print_swap(struct kvm_swap *ksw)
496{
497	int hlen, pagesize;
498	long blocksize;
499
500	pagesize = getpagesize();
501	getbsize(&hlen, &blocksize);
502	swtot.ksw_total += ksw->ksw_total;
503	swtot.ksw_used += ksw->ksw_used;
504	++nswdev;
505	if (totalflag == 0) {
506		(void)printf("%-15s %*d ",
507		    ksw->ksw_devname, hlen,
508		    CONVERT(ksw->ksw_total));
509		(void)printf("%8d %8d %5.0f%%    %s\n",
510		    CONVERT(ksw->ksw_used),
511		    CONVERT(ksw->ksw_total - ksw->ksw_used),
512		    (ksw->ksw_used * 100.0) / ksw->ksw_total,
513		    (ksw->ksw_flags & SW_SEQUENTIAL) ?
514		    "Sequential" : "Interleaved");
515	}
516}
517
518static void
519print_swap_total(void)
520{
521	int hlen, pagesize;
522	long blocksize;
523
524	pagesize = getpagesize();
525	getbsize(&hlen, &blocksize);
526	if (totalflag) {
527		blocksize = 1024 * 1024;
528		(void)printf("%dM/%dM swap space\n",
529		    CONVERT(swtot.ksw_used), CONVERT(swtot.ksw_total));
530	} else if (nswdev > 1) {
531		(void)printf("%-15s %*d %8d %8d %5.0f%%\n",
532		    "Total", hlen, CONVERT(swtot.ksw_total),
533		    CONVERT(swtot.ksw_used),
534		    CONVERT(swtot.ksw_total - swtot.ksw_used),
535		    (swtot.ksw_used * 100.0) / swtot.ksw_total);
536	}
537}
538
539static void
540swapmode_kvm(void)
541{
542	struct kvm_swap kswap[16];
543	int i, n;
544
545	n = kvm_getswapinfo(kd, kswap, sizeof kswap / sizeof kswap[0],
546	    ((swapflag > 1) ? SWIF_DUMP_TREE : 0) | SWIF_DEV_PREFIX);
547
548	print_swap_header();
549	for (i = 0; i < n; ++i)
550		print_swap(&kswap[i]);
551	print_swap_total();
552}
553
554static void
555swapmode_sysctl(void)
556{
557	struct kvm_swap ksw;
558	struct xswdev xsw;
559	size_t mibsize, size;
560	int mib[16], n;
561
562	print_swap_header();
563	mibsize = sizeof mib / sizeof mib[0];
564	if (sysctlnametomib("vm.swap_info", mib, &mibsize) == -1)
565		err(1, "sysctlnametomib()");
566	for (n = 0; ; ++n) {
567		mib[mibsize] = n;
568		size = sizeof xsw;
569		if (sysctl(mib, mibsize + 1, &xsw, &size, NULL, NULL) == -1)
570			break;
571		if (xsw.xsw_version != XSWDEV_VERSION)
572			errx(1, "xswdev version mismatch");
573		snprintf(ksw.ksw_devname, sizeof ksw.ksw_devname,
574		    "/dev/%s", devname(xsw.xsw_dev, S_IFCHR));
575		ksw.ksw_used = xsw.xsw_used;
576		ksw.ksw_total = xsw.xsw_nblks;
577		ksw.ksw_flags = xsw.xsw_flags;
578		print_swap(&ksw);
579	}
580	if (errno != ENOENT)
581		err(1, "sysctl()");
582	print_swap_total();
583}
584
585static void
586swapmode(void)
587{
588	if (kd != NULL)
589		swapmode_kvm();
590	else
591		swapmode_sysctl();
592}
593