pstat.c revision 1.71
1/*	$OpenBSD: pstat.c,v 1.71 2007/12/08 18:23:24 deraadt Exp $	*/
2/*	$NetBSD: pstat.c,v 1.27 1996/10/23 22:50:06 cgd Exp $	*/
3
4/*-
5 * Copyright (c) 1980, 1991, 1993
6 *	The Regents of the University of California.  All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the University nor the names of its contributors
17 *    may be used to endorse or promote products derived from this software
18 *    without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33#ifndef lint
34static char copyright[] =
35"@(#) Copyright (c) 1980, 1991, 1993\n\
36	The Regents of the University of California.  All rights reserved.\n";
37#endif /* not lint */
38
39#ifndef lint
40#if 0
41from: static char sccsid[] = "@(#)pstat.c	8.9 (Berkeley) 2/16/94";
42#else
43static char *rcsid = "$OpenBSD: pstat.c,v 1.71 2007/12/08 18:23:24 deraadt Exp $";
44#endif
45#endif /* not lint */
46
47#include <sys/param.h>
48#include <sys/time.h>
49#include <sys/buf.h>
50#include <sys/vnode.h>
51#include <sys/ucred.h>
52#define _KERNEL
53#include <sys/file.h>
54#include <ufs/ufs/quota.h>
55#include <ufs/ufs/inode.h>
56#define NFS
57#include <sys/mount.h>
58#undef NFS
59#undef _KERNEL
60#include <sys/stat.h>
61#include <nfs/nfsproto.h>
62#include <nfs/rpcv2.h>
63#include <nfs/nfsnode.h>
64#include <sys/ioctl.h>
65#include <sys/tty.h>
66#include <sys/conf.h>
67#include <sys/device.h>
68#include <sys/swap.h>
69
70#include <sys/sysctl.h>
71
72#include <err.h>
73#include <kvm.h>
74#include <limits.h>
75#include <nlist.h>
76#include <paths.h>
77#include <stdio.h>
78#include <stdlib.h>
79#include <string.h>
80#include <unistd.h>
81
82struct nlist vnodenl[] = {
83#define	FNL_NFILE	0		/* sysctl */
84	{"_nfiles"},
85#define FNL_MAXFILE	1		/* sysctl */
86	{"_maxfiles"},
87#define TTY_NTTY	2		/* sysctl */
88	{"_tty_count"},
89#define V_NUMV		3		/* sysctl */
90	{ "_numvnodes" },
91#define TTY_TTYLIST	4		/* sysctl */
92	{"_ttylist"},
93#define	V_MOUNTLIST	5		/* no sysctl */
94	{ "_mountlist" },
95	{ NULL }
96};
97
98struct nlist *globalnl;
99
100int	usenumflag;
101int	totalflag;
102int	kflag;
103char	*nlistf	= NULL;
104char	*memf	= NULL;
105kvm_t	*kd = NULL;
106
107#define	SVAR(var) __STRING(var)	/* to force expansion */
108#define	KGET(idx, var)							\
109	KGET1(idx, &var, sizeof(var), SVAR(var))
110#define	KGET1(idx, p, s, msg)						\
111	KGET2(globalnl[idx].n_value, p, s, msg)
112#define	KGET2(addr, p, s, msg)						\
113	if (kvm_read(kd, (u_long)(addr), p, s) != s)			\
114		warnx("cannot read %s: %s", msg, kvm_geterr(kd))
115#define	KGETRET(addr, p, s, msg)					\
116	if (kvm_read(kd, (u_long)(addr), p, s) != s) {			\
117		warnx("cannot read %s: %s", msg, kvm_geterr(kd));	\
118		return (0);						\
119	}
120
121void	filemode(void);
122int	getfiles(char **, size_t *);
123struct mount *
124	getmnt(struct mount *);
125struct e_vnode *
126	kinfo_vnodes(int *);
127struct e_vnode *
128	loadvnodes(int *);
129void	mount_print(struct mount *);
130void	nfs_header(void);
131int	nfs_print(struct vnode *);
132void	swapmode(void);
133void	ttymode(void);
134void	ttyprt(struct itty *);
135void	ufs_header(void);
136int	ufs_print(struct vnode *);
137void	ext2fs_header(void);
138int	ext2fs_print(struct vnode *);
139void	usage(void);
140void	vnode_header(void);
141void	vnode_print(struct vnode *, struct vnode *);
142void	vnodemode(void);
143
144int
145main(int argc, char *argv[])
146{
147	int fileflag = 0, swapflag = 0, ttyflag = 0, vnodeflag = 0, ch;
148	char buf[_POSIX2_LINE_MAX];
149	const char *dformat = NULL;
150	extern char *optarg;
151	extern int optind;
152	gid_t gid;
153	int i;
154
155	while ((ch = getopt(argc, argv, "d:TM:N:fiknstv")) != -1)
156		switch (ch) {
157		case 'd':
158			dformat = optarg;
159			break;
160		case 'f':
161			fileflag = 1;
162			break;
163		case 'M':
164			memf = optarg;
165			break;
166		case 'N':
167			nlistf = optarg;
168			break;
169		case 'n':
170			usenumflag = 1;
171			break;
172		case 's':
173			swapflag = 1;
174			break;
175		case 'T':
176			totalflag = 1;
177			break;
178		case 't':
179			ttyflag = 1;
180			break;
181		case 'k':
182			kflag = 1;
183			break;
184		case 'v':
185		case 'i':		/* Backward compatibility. */
186			vnodeflag = 1;
187			break;
188		default:
189			usage();
190		}
191	argc -= optind;
192	argv += optind;
193
194	if (dformat && getuid())
195		errx(1, "Only root can use -d");
196
197	if ((dformat == 0 && argc > 0) || (dformat && argc == 0))
198		usage();
199
200	/*
201	 * Discard setgid privileges if not the running kernel so that bad
202	 * guys can't print interesting stuff from kernel memory.
203	 */
204	gid = getgid();
205	if (nlistf != NULL || memf != NULL)
206		if (setresgid(gid, gid, gid) == -1)
207			err(1, "setresgid");
208
209	if (vnodeflag || dformat)
210		if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, buf)) == 0)
211			errx(1, "kvm_openfiles: %s", buf);
212
213	if (nlistf == NULL && memf == NULL)
214		if (setresgid(gid, gid, gid) == -1)
215			err(1, "setresgid");
216	if (dformat) {
217		struct nlist *nl;
218		int longformat = 0, stringformat = 0, error = 0, n;
219		int mask = ~0;
220		char format[10], buf[1024];
221
222		n = strlen(dformat);
223		if (n == 0)
224			errx(1, "illegal format");
225
226		/*
227		 * Support p, c, s, and {l, ll, h, hh, j, t, z, }[diouxX]
228		 */
229		if (strcmp(dformat, "p") == 0)
230			longformat = sizeof(long) == 8;
231		else if (strcmp(dformat, "c") == 0)
232			mask = 0xff;
233		else if (strcmp(dformat, "s") == 0)
234			stringformat = 1;
235		else if (strchr("diouxX", dformat[n - 1])) {
236			char *ptbl[]= {"l", "ll", "h", "hh", "j", "t", "z", ""};
237			int i;
238
239			char *mod;
240			for (i = 0; i < sizeof(ptbl)/sizeof(ptbl[0]); i++) {
241				mod = ptbl[i];
242				if (strlen(mod) == n - 1 &&
243				    strncmp(mod, dformat, strlen(mod)) == 0)
244					break;
245			}
246			if (i == sizeof(ptbl)/sizeof(ptbl[0])
247			    && dformat[1] != '\0')
248				errx(1, "illegal format");
249			if (strcmp(mod, "l") == 0)
250				longformat = sizeof(long) == sizeof(long long);
251			else if (strcmp(mod, "h") == 0)
252				mask = 0xffff;
253			else if (strcmp(mod, "hh") == 0)
254				mask = 0xff;
255			else
256				longformat = 1;
257
258		} else
259			errx(1, "illegal format");
260
261		if (*dformat == 's') {
262			stringformat = 1;
263			snprintf(format, sizeof(format), "%%.%zus",
264			    sizeof buf);
265		} else
266			snprintf(format, sizeof(format), "%%%s", dformat);
267
268		nl = calloc(argc + 1, sizeof *nl);
269		if (!nl)
270			err(1, "calloc nl: ");
271		for (i = 0; i < argc; i++) {
272			if (asprintf(&nl[i].n_name, "_%s",
273			    argv[i]) == -1)
274				warn("asprintf");
275		}
276		kvm_nlist(kd, nl);
277		globalnl = nl;
278		for (i = 0; i < argc; i++) {
279			long long v;
280
281			printf("%s ", argv[i]);
282			if (!nl[i].n_value && argv[i][0] == '0') {
283				nl[i].n_value = strtoul(argv[i], NULL, 16);
284				nl[i].n_type = N_DATA;
285			}
286			if (!nl[i].n_value) {
287				printf("not found\n");
288				error++;
289				continue;
290			}
291
292			printf("at %p: ", (void *)nl[i].n_value);
293			if (nl[i].n_type == N_DATA) {
294				if (stringformat) {
295					KGET1(i, &buf, sizeof(buf), argv[i]);
296					buf[sizeof(buf) - 1] = '\0';
297				} else
298					KGET1(i, &v, sizeof(v), argv[i]);
299				if (stringformat)
300					printf(format, &buf);
301				else if (longformat)
302					printf(format, v);
303				else
304					printf(format, ((int)v) & mask);
305			}
306			printf("\n");
307		}
308		for (i = 0; i < argc; i++)
309			free(nl[i].n_name);
310		free(nl);
311		exit(error);
312	}
313
314	if (vnodeflag)
315		if (kvm_nlist(kd, vnodenl) == -1)
316			errx(1, "kvm_nlist: %s", kvm_geterr(kd));
317
318	if (!(fileflag | vnodeflag | ttyflag | swapflag | totalflag || dformat))
319		usage();
320	if (fileflag || totalflag)
321		filemode();
322	if (vnodeflag || totalflag)
323		vnodemode();
324	if (ttyflag)
325		ttymode();
326	if (swapflag || totalflag)
327		swapmode();
328	exit(0);
329}
330
331void
332vnodemode(void)
333{
334	struct e_vnode *e_vnodebase, *endvnode, *evp;
335	struct vnode *vp;
336	struct mount *maddr, *mp = NULL;
337	int numvnodes;
338
339	globalnl = vnodenl;
340
341	e_vnodebase = loadvnodes(&numvnodes);
342	if (totalflag) {
343		(void)printf("%7d vnodes\n", numvnodes);
344		return;
345	}
346	endvnode = e_vnodebase + numvnodes;
347	(void)printf("%d active vnodes\n", numvnodes);
348
349	maddr = NULL;
350	for (evp = e_vnodebase; evp < endvnode; evp++) {
351		vp = &evp->vnode;
352		if (vp->v_mount != maddr) {
353			/*
354			 * New filesystem
355			 */
356			if ((mp = getmnt(vp->v_mount)) == NULL)
357				continue;
358			maddr = vp->v_mount;
359			mount_print(mp);
360			vnode_header();
361			if (!strncmp(mp->mnt_stat.f_fstypename, MOUNT_FFS, MFSNAMELEN) ||
362			    !strncmp(mp->mnt_stat.f_fstypename, MOUNT_MFS, MFSNAMELEN)) {
363				ufs_header();
364			} else if (!strncmp(mp->mnt_stat.f_fstypename, MOUNT_NFS,
365			    MFSNAMELEN)) {
366				nfs_header();
367			} else if (!strncmp(mp->mnt_stat.f_fstypename, MOUNT_EXT2FS,
368			    MFSNAMELEN)) {
369				ext2fs_header();
370			}
371			(void)printf("\n");
372		}
373		vnode_print(evp->vptr, vp);
374
375		/* Syncer vnodes have no associated fs-specific data */
376		if (vp->v_data == NULL) {
377			printf(" %6c %5c %7c\n", '-', '-', '-');
378			continue;
379		}
380
381		if (!strncmp(mp->mnt_stat.f_fstypename, MOUNT_FFS, MFSNAMELEN) ||
382		    !strncmp(mp->mnt_stat.f_fstypename, MOUNT_MFS, MFSNAMELEN)) {
383			ufs_print(vp);
384		} else if (!strncmp(mp->mnt_stat.f_fstypename, MOUNT_NFS, MFSNAMELEN)) {
385			nfs_print(vp);
386		} else if (!strncmp(mp->mnt_stat.f_fstypename, MOUNT_EXT2FS,
387		    MFSNAMELEN)) {
388			ext2fs_print(vp);
389		}
390		(void)printf("\n");
391	}
392	free(e_vnodebase);
393}
394
395void
396vnode_header(void)
397{
398	(void)printf("%*s TYP VFLAG  USE HOLD", 2 * sizeof(long), "ADDR");
399}
400
401void
402vnode_print(struct vnode *avnode, struct vnode *vp)
403{
404	char *type, flags[16];
405	char *fp = flags;
406	int flag;
407
408	/*
409	 * set type
410	 */
411	switch (vp->v_type) {
412	case VNON:
413		type = "non"; break;
414	case VREG:
415		type = "reg"; break;
416	case VDIR:
417		type = "dir"; break;
418	case VBLK:
419		type = "blk"; break;
420	case VCHR:
421		type = "chr"; break;
422	case VLNK:
423		type = "lnk"; break;
424	case VSOCK:
425		type = "soc"; break;
426	case VFIFO:
427		type = "fif"; break;
428	case VBAD:
429		type = "bad"; break;
430	default:
431		type = "unk"; break;
432	}
433	/*
434	 * gather flags
435	 */
436	flag = vp->v_flag;
437	if (flag & VROOT)
438		*fp++ = 'R';
439	if (flag & VTEXT)
440		*fp++ = 'T';
441	if (flag & VSYSTEM)
442		*fp++ = 'S';
443	if (flag & VISTTY)
444		*fp++ = 'I';
445	if (flag & VXLOCK)
446		*fp++ = 'L';
447	if (flag & VXWANT)
448		*fp++ = 'W';
449	if (vp->v_bioflag & VBIOWAIT)
450		*fp++ = 'B';
451	if (flag & VALIASED)
452		*fp++ = 'A';
453	if (vp->v_bioflag & VBIOONFREELIST)
454		*fp++ = 'F';
455	if (flag & VLOCKSWORK)
456		*fp++ = 'l';
457	if (vp->v_bioflag & VBIOONSYNCLIST)
458		*fp++ = 's';
459	if (flag == 0)
460		*fp++ = '-';
461	*fp = '\0';
462	(void)printf("%0*lx %s %5s %4d %4u", 2 * sizeof(long),
463	    (long)avnode, type, flags, vp->v_usecount, vp->v_holdcnt);
464}
465
466void
467ufs_header(void)
468{
469	(void)printf(" FILEID IFLAG RDEV|SZ");
470}
471
472int
473ufs_print(struct vnode *vp)
474{
475	int flag;
476	struct inode inode, *ip = &inode;
477	struct ufs1_dinode di1;
478	char flagbuf[16], *flags = flagbuf;
479	char *name;
480	mode_t type;
481
482	KGETRET(VTOI(vp), &inode, sizeof(struct inode), "vnode's inode");
483	KGETRET(inode.i_din1, &di1, sizeof(struct ufs1_dinode),
484	    "vnode's dinode");
485
486	inode.i_din1 = &di1;
487	flag = ip->i_flag;
488#if 0
489	if (flag & IN_LOCKED)
490		*flags++ = 'L';
491	if (flag & IN_WANTED)
492		*flags++ = 'W';
493	if (flag & IN_LWAIT)
494		*flags++ = 'Z';
495#endif
496	if (flag & IN_ACCESS)
497		*flags++ = 'A';
498	if (flag & IN_CHANGE)
499		*flags++ = 'C';
500	if (flag & IN_UPDATE)
501		*flags++ = 'U';
502	if (flag & IN_MODIFIED)
503		*flags++ = 'M';
504	if (flag & IN_RENAME)
505		*flags++ = 'R';
506	if (flag & IN_SHLOCK)
507		*flags++ = 'S';
508	if (flag & IN_EXLOCK)
509		*flags++ = 'E';
510	if (flag == 0)
511		*flags++ = '-';
512	*flags = '\0';
513
514	(void)printf(" %6d %5s", ip->i_number, flagbuf);
515	type = ip->i_ffs1_mode & S_IFMT;
516	if (S_ISCHR(ip->i_ffs1_mode) || S_ISBLK(ip->i_ffs1_mode))
517		if (usenumflag ||
518		    ((name = devname(ip->i_ffs1_rdev, type)) == NULL))
519			(void)printf("   %2d,%-2d",
520			    major(ip->i_ffs1_rdev), minor(ip->i_ffs1_rdev));
521		else
522			(void)printf(" %7s", name);
523	else
524		(void)printf(" %7qd", ip->i_ffs1_size);
525	return (0);
526}
527
528void
529ext2fs_header(void)
530{
531	(void)printf(" FILEID IFLAG SZ");
532}
533
534int
535ext2fs_print(struct vnode *vp)
536{
537	int flag;
538	struct inode inode, *ip = &inode;
539	struct ext2fs_dinode di;
540	char flagbuf[16], *flags = flagbuf;
541
542	KGETRET(VTOI(vp), &inode, sizeof(struct inode), "vnode's inode");
543	KGETRET(inode.i_e2din, &di, sizeof(struct ext2fs_dinode),
544	    "vnode's dinode");
545
546	inode.i_e2din = &di;
547	flag = ip->i_flag;
548
549#if 0
550	if (flag & IN_LOCKED)
551		*flags++ = 'L';
552	if (flag & IN_WANTED)
553		*flags++ = 'W';
554	if (flag & IN_LWAIT)
555		*flags++ = 'Z';
556#endif
557	if (flag & IN_ACCESS)
558		*flags++ = 'A';
559	if (flag & IN_CHANGE)
560		*flags++ = 'C';
561	if (flag & IN_UPDATE)
562		*flags++ = 'U';
563	if (flag & IN_MODIFIED)
564		*flags++ = 'M';
565	if (flag & IN_RENAME)
566		*flags++ = 'R';
567	if (flag & IN_SHLOCK)
568		*flags++ = 'S';
569	if (flag & IN_EXLOCK)
570		*flags++ = 'E';
571	if (flag == 0)
572		*flags++ = '-';
573	*flags = '\0';
574
575	(void)printf(" %6d %5s %2d", ip->i_number, flagbuf, ip->i_e2fs_size);
576	return (0);
577}
578
579void
580nfs_header(void)
581{
582	(void)printf(" FILEID NFLAG RDEV|SZ");
583}
584
585int
586nfs_print(struct vnode *vp)
587{
588	struct nfsnode nfsnode, *np = &nfsnode;
589	char flagbuf[16], *flags = flagbuf;
590	int flag;
591	char *name;
592	mode_t type;
593
594	KGETRET(VTONFS(vp), &nfsnode, sizeof(nfsnode), "vnode's nfsnode");
595	flag = np->n_flag;
596	if (flag & NFLUSHWANT)
597		*flags++ = 'W';
598	if (flag & NFLUSHINPROG)
599		*flags++ = 'P';
600	if (flag & NMODIFIED)
601		*flags++ = 'M';
602	if (flag & NWRITEERR)
603		*flags++ = 'E';
604	if (flag & NACC)
605		*flags++ = 'A';
606	if (flag & NUPD)
607		*flags++ = 'U';
608	if (flag & NCHG)
609		*flags++ = 'C';
610	if (flag == 0)
611		*flags++ = '-';
612	*flags = '\0';
613
614	(void)printf(" %6ld %5s", np->n_vattr.va_fileid, flagbuf);
615	type = np->n_vattr.va_mode & S_IFMT;
616	if (S_ISCHR(np->n_vattr.va_mode) || S_ISBLK(np->n_vattr.va_mode))
617		if (usenumflag ||
618		    ((name = devname(np->n_vattr.va_rdev, type)) == NULL))
619			(void)printf("   %2d,%-2d", major(np->n_vattr.va_rdev),
620			    minor(np->n_vattr.va_rdev));
621		else
622			(void)printf(" %7s", name);
623	else
624		(void)printf(" %7qd", np->n_size);
625	return (0);
626}
627
628/*
629 * Given a pointer to a mount structure in kernel space,
630 * read it in and return a usable pointer to it.
631 */
632struct mount *
633getmnt(struct mount *maddr)
634{
635	static struct mtab {
636		struct mtab *next;
637		struct mount *maddr;
638		struct mount mount;
639	} *mhead = NULL;
640	struct mtab *mt;
641
642	for (mt = mhead; mt != NULL; mt = mt->next)
643		if (maddr == mt->maddr)
644			return (&mt->mount);
645	if ((mt = malloc(sizeof(struct mtab))) == NULL)
646		err(1, "malloc: mount table");
647	KGETRET(maddr, &mt->mount, sizeof(struct mount), "mount table");
648	mt->maddr = maddr;
649	mt->next = mhead;
650	mhead = mt;
651	return (&mt->mount);
652}
653
654void
655mount_print(struct mount *mp)
656{
657	int flags;
658
659	(void)printf("*** MOUNT ");
660	(void)printf("%.*s %s on %s", MFSNAMELEN,
661	    mp->mnt_stat.f_fstypename, mp->mnt_stat.f_mntfromname,
662	    mp->mnt_stat.f_mntonname);
663	if ((flags = mp->mnt_flag)) {
664		char *comma = "(";
665
666		putchar(' ');
667		/* user visible flags */
668		if (flags & MNT_RDONLY) {
669			(void)printf("%srdonly", comma);
670			flags &= ~MNT_RDONLY;
671			comma = ",";
672		}
673		if (flags & MNT_SYNCHRONOUS) {
674			(void)printf("%ssynchronous", comma);
675			flags &= ~MNT_SYNCHRONOUS;
676			comma = ",";
677		}
678		if (flags & MNT_NOEXEC) {
679			(void)printf("%snoexec", comma);
680			flags &= ~MNT_NOEXEC;
681			comma = ",";
682		}
683		if (flags & MNT_NOSUID) {
684			(void)printf("%snosuid", comma);
685			flags &= ~MNT_NOSUID;
686			comma = ",";
687		}
688		if (flags & MNT_NODEV) {
689			(void)printf("%snodev", comma);
690			flags &= ~MNT_NODEV;
691			comma = ",";
692		}
693		if (flags & MNT_ASYNC) {
694			(void)printf("%sasync", comma);
695			flags &= ~MNT_ASYNC;
696			comma = ",";
697		}
698		if (flags & MNT_EXRDONLY) {
699			(void)printf("%sexrdonly", comma);
700			flags &= ~MNT_EXRDONLY;
701			comma = ",";
702		}
703		if (flags & MNT_EXPORTED) {
704			(void)printf("%sexport", comma);
705			flags &= ~MNT_EXPORTED;
706			comma = ",";
707		}
708		if (flags & MNT_DEFEXPORTED) {
709			(void)printf("%sdefdexported", comma);
710			flags &= ~MNT_DEFEXPORTED;
711			comma = ",";
712		}
713		if (flags & MNT_EXPORTANON) {
714			(void)printf("%sexportanon", comma);
715			flags &= ~MNT_EXPORTANON;
716			comma = ",";
717		}
718		if (flags & MNT_EXKERB) {
719			(void)printf("%sexkerb", comma);
720			flags &= ~MNT_EXKERB;
721			comma = ",";
722		}
723		if (flags & MNT_LOCAL) {
724			(void)printf("%slocal", comma);
725			flags &= ~MNT_LOCAL;
726			comma = ",";
727		}
728		if (flags & MNT_QUOTA) {
729			(void)printf("%squota", comma);
730			flags &= ~MNT_QUOTA;
731			comma = ",";
732		}
733		if (flags & MNT_ROOTFS) {
734			(void)printf("%srootfs", comma);
735			flags &= ~MNT_ROOTFS;
736			comma = ",";
737		}
738		if (flags & MNT_NOATIME) {
739			(void)printf("%snoatime", comma);
740			flags &= ~MNT_NOATIME;
741			comma = ",";
742		}
743		/* filesystem control flags */
744		if (flags & MNT_UPDATE) {
745			(void)printf("%supdate", comma);
746			flags &= ~MNT_UPDATE;
747			comma = ",";
748		}
749		if (flags & MNT_DELEXPORT) {
750			(void)printf("%sdelexport", comma);
751			flags &= ~MNT_DELEXPORT;
752			comma = ",";
753		}
754		if (flags & MNT_RELOAD) {
755			(void)printf("%sreload", comma);
756			flags &= ~MNT_RELOAD;
757			comma = ",";
758		}
759		if (flags & MNT_FORCE) {
760			(void)printf("%sforce", comma);
761			flags &= ~MNT_FORCE;
762			comma = ",";
763		}
764		if (flags & MNT_WANTRDWR) {
765			(void)printf("%swantrdwr", comma);
766			flags &= ~MNT_WANTRDWR;
767			comma = ",";
768		}
769		if (flags & MNT_SOFTDEP) {
770			(void)printf("%ssoftdep", comma);
771			flags &= ~MNT_SOFTDEP;
772			comma = ",";
773		}
774		if (flags)
775			(void)printf("%sunknown_flags:%x", comma, flags);
776		(void)printf(")");
777	}
778	(void)printf("\n");
779}
780
781struct e_vnode *
782loadvnodes(int *avnodes)
783{
784	int mib[2];
785	size_t copysize;
786	struct e_vnode *vnodebase;
787
788	if (memf != NULL) {
789		/*
790		 * do it by hand
791		 */
792		return (kinfo_vnodes(avnodes));
793	}
794	mib[0] = CTL_KERN;
795	mib[1] = KERN_VNODE;
796	if (sysctl(mib, 2, NULL, &copysize, NULL, 0) == -1)
797		err(1, "sysctl: KERN_VNODE");
798	if ((vnodebase = malloc(copysize)) == NULL)
799		err(1, "malloc: vnode table");
800	if (sysctl(mib, 2, vnodebase, &copysize, NULL, 0) == -1)
801		err(1, "sysctl: KERN_VNODE");
802	if (copysize % sizeof(struct e_vnode))
803		errx(1, "vnode size mismatch");
804	*avnodes = copysize / sizeof(struct e_vnode);
805
806	return (vnodebase);
807}
808
809/*
810 * simulate what a running kernel does in kinfo_vnode
811 */
812struct e_vnode *
813kinfo_vnodes(int *avnodes)
814{
815	struct mntlist kvm_mountlist;
816	struct mount *mp, mount;
817	struct vnode *vp, vnode;
818	char *vbuf, *evbuf, *bp;
819	int mib[2], numvnodes;
820	size_t num;
821
822	if (kd == 0) {
823		mib[0] = CTL_KERN;
824		mib[1] = KERN_NUMVNODES;
825		num = sizeof(numvnodes);
826		if (sysctl(mib, 2, &numvnodes, &num, NULL, 0) < 0)
827			err(1, "sysctl(KERN_NUMVNODES) failed");
828	} else
829		KGET(V_NUMV, numvnodes);
830	if ((vbuf = calloc(numvnodes + 20,
831	    sizeof(struct vnode *) + sizeof(struct vnode))) == NULL)
832		err(1, "malloc: vnode buffer");
833	bp = vbuf;
834	evbuf = vbuf + (numvnodes + 20) *
835	    (sizeof(struct vnode *) + sizeof(struct vnode));
836	KGET(V_MOUNTLIST, kvm_mountlist);
837	for (num = 0, mp = CIRCLEQ_FIRST(&kvm_mountlist); ;
838	    mp = CIRCLEQ_NEXT(&mount, mnt_list)) {
839		KGET2(mp, &mount, sizeof(mount), "mount entry");
840		for (vp = LIST_FIRST(&mount.mnt_vnodelist);
841		    vp != NULL; vp = LIST_NEXT(&vnode, v_mntvnodes)) {
842			KGET2(vp, &vnode, sizeof(vnode), "vnode");
843			if ((bp + sizeof(struct vnode *) +
844			    sizeof(struct vnode)) > evbuf)
845				/* XXX - should realloc */
846				errx(1, "no more room for vnodes");
847			memmove(bp, &vp, sizeof(struct vnode *));
848			bp += sizeof(struct vnode *);
849			memmove(bp, &vnode, sizeof(struct vnode));
850			bp += sizeof(struct vnode);
851			num++;
852		}
853		if (mp == CIRCLEQ_LAST(&kvm_mountlist))
854			break;
855	}
856	*avnodes = num;
857	return ((struct e_vnode *)vbuf);
858}
859
860const char hdr[] =
861"   LINE RAW  CAN  OUT  HWT LWT    COL STATE      SESS  PGID DISC\n";
862
863void
864tty2itty(struct tty *tp, struct itty *itp)
865{
866	itp->t_dev = tp->t_dev;
867	itp->t_rawq_c_cc = tp->t_rawq.c_cc;
868	itp->t_canq_c_cc = tp->t_canq.c_cc;
869	itp->t_outq_c_cc = tp->t_outq.c_cc;
870	itp->t_hiwat = tp->t_hiwat;
871	itp->t_lowat = tp->t_lowat;
872	itp->t_column = tp->t_column;
873	itp->t_state = tp->t_state;
874	itp->t_session = tp->t_session;
875	if (tp->t_pgrp != NULL)
876		KGET2(&tp->t_pgrp->pg_id, &itp->t_pgrp_pg_id, sizeof(pid_t), "pgid");
877	itp->t_line = tp->t_line;
878}
879
880void
881ttymode(void)
882{
883	struct ttylist_head tty_head;
884	struct tty *tp, tty;
885	int mib[3], ntty, i;
886	struct itty itty, *itp;
887	size_t nlen;
888
889	if (kd == 0) {
890		mib[0] = CTL_KERN;
891		mib[1] = KERN_TTYCOUNT;
892		nlen = sizeof(ntty);
893		if (sysctl(mib, 2, &ntty, &nlen, NULL, 0) < 0)
894			err(1, "sysctl(KERN_TTYCOUNT) failed");
895	} else
896		KGET(TTY_NTTY, ntty);
897	(void)printf("%d terminal device%s\n", ntty, ntty == 1 ? "" : "s");
898	(void)printf("%s", hdr);
899	if (kd == 0) {
900		mib[0] = CTL_KERN;
901		mib[1] = KERN_TTY;
902		mib[2] = KERN_TTY_INFO;
903		nlen = ntty * sizeof(struct itty);
904		if ((itp = malloc(nlen)) == NULL)
905			err(1, "malloc");
906		if (sysctl(mib, 3, itp, &nlen, NULL, 0) < 0)
907			err(1, "sysctl(KERN_TTY_INFO) failed");
908		for (i = 0; i < ntty; i++)
909			ttyprt(&itp[i]);
910		free(itp);
911	} else {
912		KGET(TTY_TTYLIST, tty_head);
913		for (tp = TAILQ_FIRST(&tty_head); tp;
914		    tp = TAILQ_NEXT(&tty, tty_link)) {
915			KGET2(tp, &tty, sizeof tty, "tty struct");
916			tty2itty(&tty, &itty);
917			ttyprt(&itty);
918		}
919	}
920}
921
922struct {
923	int flag;
924	char val;
925} ttystates[] = {
926	{ TS_WOPEN,	'W'},
927	{ TS_ISOPEN,	'O'},
928	{ TS_CARR_ON,	'C'},
929	{ TS_TIMEOUT,	'T'},
930	{ TS_FLUSH,	'F'},
931	{ TS_BUSY,	'B'},
932	{ TS_ASLEEP,	'A'},
933	{ TS_XCLUDE,	'X'},
934	{ TS_TTSTOP,	'S'},
935	{ TS_TBLOCK,	'K'},
936	{ TS_ASYNC,	'Y'},
937	{ TS_BKSL,	'D'},
938	{ TS_ERASE,	'E'},
939	{ TS_LNCH,	'L'},
940	{ TS_TYPEN,	'P'},
941	{ TS_CNTTB,	'N'},
942	{ 0,		'\0'},
943};
944
945void
946ttyprt(struct itty *tp)
947{
948	char *name, state[20];
949	int i, j;
950
951	if (usenumflag || (name = devname(tp->t_dev, S_IFCHR)) == NULL)
952		(void)printf("%2d,%-3d   ", major(tp->t_dev), minor(tp->t_dev));
953	else
954		(void)printf("%7s ", name);
955	(void)printf("%3d %4d ", tp->t_rawq_c_cc, tp->t_canq_c_cc);
956	(void)printf("%4d %4d %3d %6d ", tp->t_outq_c_cc,
957		tp->t_hiwat, tp->t_lowat, tp->t_column);
958	for (i = j = 0; ttystates[i].flag; i++)
959		if (tp->t_state&ttystates[i].flag)
960			state[j++] = ttystates[i].val;
961	if (j == 0)
962		state[j++] = '-';
963	state[j] = '\0';
964	(void)printf("%-6s %8lx", state, (u_long)tp->t_session & ~KERNBASE);
965	(void)printf("%6d ", tp->t_pgrp_pg_id);
966	switch (tp->t_line) {
967	case TTYDISC:
968		(void)printf("term\n");
969		break;
970	case TABLDISC:
971		(void)printf("tab\n");
972		break;
973	case SLIPDISC:
974		(void)printf("slip\n");
975		break;
976	case PPPDISC:
977		(void)printf("ppp\n");
978		break;
979	case STRIPDISC:
980		(void)printf("strip\n");
981		break;
982	case NMEADISC:
983		(void)printf("nmea\n");
984		break;
985	default:
986		(void)printf("%d\n", tp->t_line);
987		break;
988	}
989}
990
991void
992filemode(void)
993{
994	struct file fp, *ffp, *addr;
995	char *buf, flagbuf[16], *fbp;
996	static char *dtypes[] = { "???", "inode", "socket" };
997	int mib[2], maxfile, nfile;
998	size_t len;
999
1000	if (kd == 0) {
1001		mib[0] = CTL_KERN;
1002		mib[1] = KERN_MAXFILES;
1003		len = sizeof(maxfile);
1004		if (sysctl(mib, 2, &maxfile, &len, NULL, 0) < 0)
1005			err(1, "sysctl(KERN_MAXFILES) failed");
1006		if (totalflag) {
1007			mib[0] = CTL_KERN;
1008			mib[1] = KERN_NFILES;
1009			len = sizeof(nfile);
1010			if (sysctl(mib, 2, &nfile, &len, NULL, 0) < 0)
1011				err(1, "sysctl(KERN_NFILES) failed");
1012		}
1013	} else {
1014		KGET(FNL_MAXFILE, maxfile);
1015		if (totalflag) {
1016			KGET(FNL_NFILE, nfile);
1017			(void)printf("%3d/%3d files\n", nfile, maxfile);
1018			return;
1019		}
1020	}
1021
1022	if (getfiles(&buf, &len) == -1)
1023		return;
1024	/*
1025	 * Getfiles returns in malloc'd memory a pointer to the first file
1026	 * structure, and then an array of file structs (whose addresses are
1027	 * derivable from the previous entry).
1028	 */
1029	addr = LIST_FIRST((struct filelist *)buf);
1030	ffp = (struct file *)(buf + sizeof(struct filelist));
1031	nfile = (len - sizeof(struct filelist)) / sizeof(struct file);
1032
1033	(void)printf("%d/%d open files\n", nfile, maxfile);
1034
1035	(void)printf("%*s TYPE       FLG  CNT  MSG  %*s  OFFSET\n",
1036	    2 * sizeof(long), "LOC", 2 * sizeof(long), "DATA");
1037	for (; (char *)ffp < buf + len; addr = LIST_NEXT(ffp, f_list), ffp++) {
1038		memmove(&fp, ffp, sizeof fp);
1039		if ((unsigned)fp.f_type > DTYPE_SOCKET)
1040			continue;
1041		(void)printf("%0*lx ", 2 * sizeof(long), (long)addr);
1042		(void)printf("%-8.8s", dtypes[fp.f_type]);
1043		fbp = flagbuf;
1044		if (fp.f_flag & FREAD)
1045			*fbp++ = 'R';
1046		if (fp.f_flag & FWRITE)
1047			*fbp++ = 'W';
1048		if (fp.f_flag & FAPPEND)
1049			*fbp++ = 'A';
1050		if (fp.f_flag & FHASLOCK)
1051			*fbp++ = 'L';
1052		if (fp.f_flag & FASYNC)
1053			*fbp++ = 'I';
1054		*fbp = '\0';
1055		(void)printf("%6s  %3ld", flagbuf, fp.f_count);
1056		(void)printf("  %3ld", fp.f_msgcount);
1057		(void)printf("  %0*lx", 2 * sizeof(long), (long)fp.f_data);
1058
1059		if (fp.f_offset < 0)
1060			(void)printf("  %llx\n", (long long)fp.f_offset);
1061		else
1062			(void)printf("  %lld\n", (long long)fp.f_offset);
1063	}
1064	free(buf);
1065}
1066
1067int
1068getfiles(char **abuf, size_t *alen)
1069{
1070	size_t len;
1071	int mib[2];
1072	char *buf;
1073
1074	/*
1075	 * XXX
1076	 * Add emulation of KINFO_FILE here.
1077	 */
1078	if (memf != NULL)
1079		errx(1, "files on dead kernel, not implemented");
1080
1081	mib[0] = CTL_KERN;
1082	mib[1] = KERN_FILE;
1083	if (sysctl(mib, 2, NULL, &len, NULL, 0) == -1) {
1084		warn("sysctl: KERN_FILE");
1085		return (-1);
1086	}
1087	if ((buf = malloc(len)) == NULL)
1088		err(1, "malloc: KERN_FILE");
1089	if (sysctl(mib, 2, buf, &len, NULL, 0) == -1) {
1090		warn("sysctl: KERN_FILE");
1091		free(buf);
1092		return (-1);
1093	}
1094	*abuf = buf;
1095	*alen = len;
1096	return (0);
1097}
1098
1099/*
1100 * swapmode is based on a program called swapinfo written
1101 * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
1102 */
1103void
1104swapmode(void)
1105{
1106	char *header;
1107	int hlen = 10, nswap;
1108	int bdiv, i, avail, nfree, npfree, used;
1109	long blocksize;
1110	struct swapent *swdev;
1111
1112	if (kflag) {
1113		header = "1K-blocks";
1114		blocksize = 1024;
1115		hlen = strlen(header);
1116	} else
1117		header = getbsize(&hlen, &blocksize);
1118
1119	nswap = swapctl(SWAP_NSWAP, 0, 0);
1120	if (nswap == 0) {
1121		if (!totalflag)
1122			(void)printf("%-11s %*s %8s %8s %8s  %s\n",
1123			    "Device", hlen, header,
1124			    "Used", "Avail", "Capacity", "Priority");
1125		(void)printf("%-11s %*d %8d %8d %5.0f%%\n",
1126		    "Total", hlen, 0, 0, 0, 0.0);
1127		return;
1128	}
1129	if ((swdev = calloc(nswap, sizeof(*swdev))) == NULL)
1130		err(1, "malloc");
1131	if (swapctl(SWAP_STATS, swdev, nswap) == -1)
1132		err(1, "swapctl");
1133
1134	if (!totalflag)
1135		(void)printf("%-11s %*s %8s %8s %8s  %s\n",
1136		    "Device", hlen, header,
1137		    "Used", "Avail", "Capacity", "Priority");
1138
1139	/* Run through swap list, doing the funky monkey. */
1140	bdiv = blocksize / DEV_BSIZE;
1141	avail = nfree = npfree = 0;
1142	for (i = 0; i < nswap; i++) {
1143		int xsize, xfree;
1144
1145		if (!(swdev[i].se_flags & SWF_ENABLE))
1146			continue;
1147
1148		if (!totalflag) {
1149			if (usenumflag)
1150				(void)printf("%2d,%-2d       %*d ",
1151				    major(swdev[i].se_dev),
1152				    minor(swdev[i].se_dev),
1153				    hlen, swdev[i].se_nblks / bdiv);
1154			else
1155				(void)printf("%-11s %*d ", swdev[i].se_path,
1156				    hlen, swdev[i].se_nblks / bdiv);
1157		}
1158
1159		xsize = swdev[i].se_nblks;
1160		used = swdev[i].se_inuse;
1161		xfree = xsize - used;
1162		nfree += (xsize - used);
1163		npfree++;
1164		avail += xsize;
1165		if (totalflag)
1166			continue;
1167		(void)printf("%8d %8d %5.0f%%    %d\n",
1168		    used / bdiv, xfree / bdiv,
1169		    (double)used / (double)xsize * 100.0,
1170		    swdev[i].se_priority);
1171	}
1172	free(swdev);
1173
1174	/*
1175	 * If only one partition has been set up via swapon(8), we don't
1176	 * need to bother with totals.
1177	 */
1178	used = avail - nfree;
1179	if (totalflag) {
1180		(void)printf("%dM/%dM swap space\n",
1181		    used / (1048576 / DEV_BSIZE),
1182		    avail / (1048576 / DEV_BSIZE));
1183		return;
1184	}
1185	if (npfree > 1) {
1186		(void)printf("%-11s %*d %8d %8d %5.0f%%\n",
1187		    "Total", hlen, avail / bdiv, used / bdiv, nfree / bdiv,
1188		    (double)used / (double)avail * 100.0);
1189	}
1190}
1191
1192void
1193usage(void)
1194{
1195	(void)fprintf(stderr,
1196	    "usage: pstat [-fknsTtv] [-d format] [-M core] [-N system] [symbols ...]\n");
1197	exit(1);
1198}
1199