pstat.c revision 97378
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#ifndef lint
42static const char copyright[] =
43"@(#) Copyright (c) 1980, 1991, 1993, 1994\n\
44	The Regents of the University of California.  All rights reserved.\n";
45#endif /* not lint */
46
47#ifndef lint
48#if 0
49static char sccsid[] = "@(#)pstat.c	8.16 (Berkeley) 5/9/95";
50#endif
51static const char rcsid[] =
52  "$FreeBSD: head/usr.sbin/pstat/pstat.c 97378 2002-05-28 06:52:21Z des $";
53#endif /* not lint */
54
55#include <sys/param.h>
56#include <sys/time.h>
57#define _KERNEL
58#include <sys/file.h>
59#include <sys/uio.h>
60#undef _KERNEL
61#include <sys/stat.h>
62#include <sys/stdint.h>
63#include <sys/ioctl.h>
64#include <sys/ioctl_compat.h>	/* XXX NTTYDISC is too well hidden */
65#include <sys/tty.h>
66#include <sys/conf.h>
67#include <sys/blist.h>
68
69#include <sys/user.h>
70#include <sys/sysctl.h>
71
72#include <err.h>
73#include <fcntl.h>
74#include <kvm.h>
75#include <limits.h>
76#include <nlist.h>
77#include <stdio.h>
78#include <stdlib.h>
79#include <string.h>
80#include <unistd.h>
81
82enum {
83	NL_CONSTTY,
84	NL_MAXFILES,
85	NL_NFILES,
86	NL_TTY_LIST
87};
88
89static struct nlist nl[] = {
90	{ "_constty", 0 },
91	{ "_maxfiles", 0 },
92	{ "_nfiles", 0 },
93	{ "_tty_list", 0 },
94	{ "" }
95};
96
97static int	usenumflag;
98static int	totalflag;
99static int	swapflag;
100static char	*nlistf;
101static char	*memf;
102static kvm_t	*kd;
103
104static char	*usagestr;
105
106static void	filemode(void);
107static int	getfiles(char **, size_t *);
108static void	swapmode(void);
109static void	ttymode(void);
110static void	ttyprt(struct xtty *);
111static void	usage(void);
112
113int
114main(int argc, char *argv[])
115{
116	int ch, i, quit, ret;
117	int fileflag, ttyflag;
118	char buf[_POSIX2_LINE_MAX],*opts;
119
120	fileflag = swapflag = ttyflag = 0;
121
122	/* We will behave like good old swapinfo if thus invoked */
123	opts = strrchr(argv[0], '/');
124	if (opts)
125		opts++;
126	else
127		opts = argv[0];
128	if (!strcmp(opts, "swapinfo")) {
129		swapflag = 1;
130		opts = "kM:N:";
131		usagestr = "swapinfo [-k] [-M core] [-N system]";
132	} else {
133		opts = "TM:N:fknst";
134		usagestr = "pstat [-Tfknst] [-M core] [-N system]";
135	}
136
137	while ((ch = getopt(argc, argv, opts)) != -1)
138		switch (ch) {
139		case 'f':
140			fileflag = 1;
141			break;
142		case 'k':
143			putenv("BLOCKSIZE=1K");
144			break;
145		case 'M':
146			memf = optarg;
147			break;
148		case 'N':
149			nlistf = optarg;
150			break;
151		case 'n':
152			usenumflag = 1;
153			break;
154		case 's':
155			++swapflag;
156			break;
157		case 'T':
158			totalflag = 1;
159			break;
160		case 't':
161			ttyflag = 1;
162			break;
163		default:
164			usage();
165		}
166	argc -= optind;
167	argv += optind;
168
169	if (memf != NULL) {
170		kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, buf);
171		if (kd == NULL)
172			errx(1, "kvm_openfiles: %s", buf);
173		if ((ret = kvm_nlist(kd, nl)) != 0) {
174			if (ret == -1)
175				errx(1, "kvm_nlist: %s", kvm_geterr(kd));
176			quit = 0;
177			for (i = 0; nl[i].n_name[0] != '\0'; ++i)
178				if (nl[i].n_value == 0) {
179					quit = 1;
180					warnx("undefined symbol: %s",
181					    nl[i].n_name);
182				}
183			if (quit)
184				exit(1);
185		}
186	}
187	if (!(fileflag | ttyflag | swapflag | totalflag))
188		usage();
189	if (fileflag || totalflag)
190		filemode();
191	if (ttyflag)
192		ttymode();
193	if (swapflag || totalflag)
194		swapmode();
195	exit (0);
196}
197
198static void
199usage(void)
200{
201	fprintf(stderr, "usage: %s\n", usagestr);
202	exit (1);
203}
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	SLIST_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 = SLIST_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 = tty.t_list.sle_next;
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		(void)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 file *fp;
379	struct file *addr;
380	char *buf, flagbuf[16], *fbp;
381	int maxf, openf;
382	size_t len;
383	static char *dtypes[] = { "???", "inode", "socket" };
384
385	if (kd != NULL) {
386		if (kvm_read(kd, nl[NL_MAXFILES].n_value,
387			&maxf, sizeof maxf) != sizeof maxf ||
388		    kvm_read(kd, nl[NL_NFILES].n_value,
389			&openf, sizeof openf) != sizeof openf)
390			errx(1, "kvm_read(): %s", kvm_geterr(kd));
391	} else {
392		len = sizeof(int);
393		if (sysctlbyname("kern.maxfiles", &maxf, &len, 0, 0) == -1 ||
394		    sysctlbyname("kern.openfiles", &openf, &len, 0, 0) == -1)
395			err(1, "sysctlbyname()");
396	}
397
398	if (totalflag) {
399		(void)printf("%3d/%3d files\n", openf, maxf);
400		return;
401	}
402	if (getfiles(&buf, &len) == -1)
403		return;
404	/*
405	 * Getfiles returns in malloc'd memory a pointer to the first file
406	 * structure, and then an array of file structs (whose addresses are
407	 * derivable from the previous entry).
408	 */
409	addr = LIST_FIRST((struct filelist *)buf);
410	fp = (struct file *)(buf + sizeof(struct filelist));
411	openf = (len - sizeof(struct filelist)) / sizeof(struct file);
412
413	(void)printf("%d/%d open files\n", openf, maxf);
414	(void)printf("   LOC   TYPE    FLG     CNT  MSG    DATA    OFFSET\n");
415	for (; (char *)fp < buf + len; addr = LIST_NEXT(fp, f_list), fp++) {
416		if ((unsigned)fp->f_type > DTYPE_SOCKET)
417			continue;
418		(void)printf("%8lx ", (u_long)(void *)addr);
419		(void)printf("%-8.8s", dtypes[fp->f_type]);
420		fbp = flagbuf;
421		if (fp->f_flag & FREAD)
422			*fbp++ = 'R';
423		if (fp->f_flag & FWRITE)
424			*fbp++ = 'W';
425		if (fp->f_flag & FAPPEND)
426			*fbp++ = 'A';
427		if (fp->f_flag & FASYNC)
428			*fbp++ = 'I';
429		*fbp = '\0';
430		(void)printf("%6s  %3d", flagbuf, fp->f_count);
431		(void)printf("  %3d", fp->f_msgcount);
432		(void)printf("  %8lx", (u_long)(void *)fp->f_data);
433		(void)printf("  %jx\n", (uintmax_t)fp->f_offset);
434	}
435	free(buf);
436}
437
438static int
439getfiles(char **abuf, size_t *alen)
440{
441	size_t len;
442	int mib[2];
443	char *buf;
444
445	/*
446	 * XXX
447	 * Add emulation of KINFO_FILE here.
448	 */
449	if (kd != NULL)
450		errx(1, "files on dead kernel, not implemented");
451
452	mib[0] = CTL_KERN;
453	mib[1] = KERN_FILE;
454	if (sysctl(mib, 2, NULL, &len, NULL, 0) == -1) {
455		warn("sysctl: KERN_FILE");
456		return (-1);
457	}
458	if ((buf = malloc(len)) == NULL)
459		errx(1, "malloc");
460	if (sysctl(mib, 2, buf, &len, NULL, 0) == -1) {
461		warn("sysctl: KERN_FILE");
462		return (-1);
463	}
464	*abuf = buf;
465	*alen = len;
466	return (0);
467}
468
469/*
470 * swapmode is based on a program called swapinfo written
471 * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
472 */
473
474#define CONVERT(v)	((int)((intmax_t)(v) * pagesize / blocksize))
475static struct kvm_swap swtot;
476static int nswdev;
477
478static void
479print_swap_header(void)
480{
481	int hlen;
482	long blocksize;
483	const char *header;
484
485	header = getbsize(&hlen, &blocksize);
486	if (totalflag == 0)
487		(void)printf("%-15s %*s %8s %8s %8s  %s\n",
488		    "Device", hlen, header,
489		    "Used", "Avail", "Capacity", "Type");
490}
491
492static void
493print_swap(struct kvm_swap *ksw)
494{
495	int hlen, pagesize;
496	long blocksize;
497
498	pagesize = getpagesize();
499	getbsize(&hlen, &blocksize);
500	swtot.ksw_total += ksw->ksw_total;
501	swtot.ksw_used += ksw->ksw_used;
502	++nswdev;
503	if (totalflag == 0) {
504		(void)printf("%-15s %*d ",
505		    ksw->ksw_devname, hlen,
506		    CONVERT(ksw->ksw_total));
507		(void)printf("%8d %8d %5.0f%%    %s\n",
508		    CONVERT(ksw->ksw_used),
509		    CONVERT(ksw->ksw_total - ksw->ksw_used),
510		    (ksw->ksw_used * 100.0) / ksw->ksw_total,
511		    (ksw->ksw_flags & SW_SEQUENTIAL) ?
512		    "Sequential" : "Interleaved");
513	}
514}
515
516static void
517print_swap_total(void)
518{
519	int hlen, pagesize;
520	long blocksize;
521
522	pagesize = getpagesize();
523	getbsize(&hlen, &blocksize);
524	if (totalflag) {
525		blocksize = 1024 * 1024;
526		(void)printf("%dM/%dM swap space\n",
527		    CONVERT(swtot.ksw_used), CONVERT(swtot.ksw_total));
528	} else if (nswdev > 1) {
529		(void)printf("%-15s %*d %8d %8d %5.0f%%\n",
530		    "Total", hlen, CONVERT(swtot.ksw_total),
531		    CONVERT(swtot.ksw_used),
532		    CONVERT(swtot.ksw_total - swtot.ksw_used),
533		    (swtot.ksw_used * 100.0) / swtot.ksw_total);
534	}
535}
536
537static void
538swapmode_kvm(void)
539{
540	struct kvm_swap kswap[16];
541	int i, n;
542
543	n = kvm_getswapinfo(kd, kswap, sizeof kswap / sizeof kswap[0],
544	    ((swapflag > 1) ? SWIF_DUMP_TREE : 0) | SWIF_DEV_PREFIX);
545
546	print_swap_header();
547	for (i = 0; i < n; ++i)
548		print_swap(&kswap[i]);
549	print_swap_total();
550}
551
552static void
553swapmode_sysctl(void)
554{
555	struct kvm_swap ksw;
556	struct xswdev xsw;
557	size_t mibsize, size;
558	int mib[16], n;
559
560	print_swap_header();
561	mibsize = sizeof mib / sizeof mib[0];
562	if (sysctlnametomib("vm.swap_info", mib, &mibsize) == -1)
563		err(1, "sysctlnametomib()");
564	for (n = 0; ; ++n) {
565		mib[mibsize] = n;
566		size = sizeof xsw;
567		if (sysctl(mib, mibsize + 1, &xsw, &size, NULL, NULL) == -1)
568			break;
569		if (xsw.xsw_version != XSWDEV_VERSION)
570			errx(1, "xswdev version mismatch");
571		snprintf(ksw.ksw_devname, sizeof ksw.ksw_devname,
572		    "/dev/%s", devname(xsw.xsw_dev, S_IFCHR));
573		ksw.ksw_used = xsw.xsw_used;
574		ksw.ksw_total = xsw.xsw_nblks;
575		ksw.ksw_flags = xsw.xsw_flags;
576		print_swap(&ksw);
577	}
578	if (errno != ENOENT)
579		err(1, "sysctl()");
580	print_swap_total();
581}
582
583static void
584swapmode(void)
585{
586	if (kd != NULL)
587		swapmode_kvm();
588	else
589		swapmode_sysctl();
590}
591