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