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