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