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