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