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