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