xref: /netbsd-src/usr.sbin/pstat/pstat.c (revision 76dfffe33547c37f8bdd446e3e4ab0f3c16cea4b)
1 /*	$NetBSD: pstat.c,v 1.27 1996/10/23 22:50:06 cgd Exp $	*/
2 
3 /*-
4  * Copyright (c) 1980, 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by the University of
18  *	California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #ifndef lint
37 static char copyright[] =
38 "@(#) Copyright (c) 1980, 1991, 1993\n\
39 	The Regents of the University of California.  All rights reserved.\n";
40 #endif /* not lint */
41 
42 #ifndef lint
43 #if 0
44 from: static char sccsid[] = "@(#)pstat.c	8.9 (Berkeley) 2/16/94";
45 #else
46 static char *rcsid = "$NetBSD: pstat.c,v 1.27 1996/10/23 22:50:06 cgd Exp $";
47 #endif
48 #endif /* not lint */
49 
50 #include <sys/param.h>
51 #include <sys/time.h>
52 #include <sys/vnode.h>
53 #include <sys/map.h>
54 #include <sys/ucred.h>
55 #define _KERNEL
56 #include <sys/file.h>
57 #include <ufs/ufs/quota.h>
58 #include <ufs/ufs/inode.h>
59 #define NFS
60 #include <sys/mount.h>
61 #undef NFS
62 #undef _KERNEL
63 #include <sys/stat.h>
64 #include <nfs/nfsproto.h>
65 #include <nfs/rpcv2.h>
66 #include <nfs/nfsnode.h>
67 #include <sys/ioctl.h>
68 #include <sys/tty.h>
69 #include <sys/conf.h>
70 #include <sys/device.h>
71 
72 #include <sys/sysctl.h>
73 
74 #include <err.h>
75 #include <kvm.h>
76 #include <limits.h>
77 #include <nlist.h>
78 #include <stdio.h>
79 #include <stdlib.h>
80 #include <string.h>
81 #include <unistd.h>
82 
83 struct nlist nl[] = {
84 #define VM_SWAPMAP	0
85 	{ "_swapmap" },	/* list of free swap areas */
86 #define VM_NSWAPMAP	1
87 	{ "_nswapmap" },/* size of the swap map */
88 #define VM_SWDEVT	2
89 	{ "_swdevt" },	/* list of swap devices and sizes */
90 #define VM_NSWAP	3
91 	{ "_nswap" },	/* size of largest swap device */
92 #define VM_NSWDEV	4
93 	{ "_nswdev" },	/* number of swap devices */
94 #define VM_DMMAX	5
95 	{ "_dmmax" },	/* maximum size of a swap block */
96 #define	V_MOUNTLIST	6
97 	{ "_mountlist" },	/* address of head of mount list. */
98 #define V_NUMV		7
99 	{ "_numvnodes" },
100 #define	FNL_NFILE	8
101 	{"_nfiles"},
102 #define FNL_MAXFILE	9
103 	{"_maxfiles"},
104 #define TTY_NTTY	10
105 	{"_tty_count"},
106 #define TTY_TTYLIST	11
107 	{"_ttylist"},
108 #define NLMANDATORY TTY_TTYLIST	/* names up to here are mandatory */
109 #define VM_NISWAP	NLMANDATORY + 1
110 	{ "_niswap" },
111 #define VM_NISWDEV	NLMANDATORY + 2
112 	{ "_niswdev" },
113 	{ "" }
114 };
115 
116 int	usenumflag;
117 int	totalflag;
118 int	kflag;
119 char	*nlistf	= NULL;
120 char	*memf	= NULL;
121 kvm_t	*kd;
122 
123 #define	SVAR(var) __STRING(var)	/* to force expansion */
124 #define	KGET(idx, var)							\
125 	KGET1(idx, &var, sizeof(var), SVAR(var))
126 #define	KGET1(idx, p, s, msg)						\
127 	KGET2(nl[idx].n_value, p, s, msg)
128 #define	KGET2(addr, p, s, msg)						\
129 	if (kvm_read(kd, (u_long)(addr), p, s) != s)			\
130 		warnx("cannot read %s: %s", msg, kvm_geterr(kd))
131 #define	KGETRET(addr, p, s, msg)					\
132 	if (kvm_read(kd, (u_long)(addr), p, s) != s) {			\
133 		warnx("cannot read %s: %s", msg, kvm_geterr(kd));	\
134 		return (0);						\
135 	}
136 
137 void	filemode __P((void));
138 int	getfiles __P((char **, int *));
139 struct mount *
140 	getmnt __P((struct mount *));
141 struct e_vnode *
142 	kinfo_vnodes __P((int *));
143 struct e_vnode *
144 	loadvnodes __P((int *));
145 void	mount_print __P((struct mount *));
146 void	nfs_header __P((void));
147 int	nfs_print __P((struct vnode *));
148 void	swapmode __P((void));
149 void	ttymode __P((void));
150 void	ttyprt __P((struct tty *));
151 void	ufs_header __P((void));
152 int	ufs_print __P((struct vnode *));
153 void	usage __P((void));
154 void	vnode_header __P((void));
155 void	vnode_print __P((struct vnode *, struct vnode *));
156 void	vnodemode __P((void));
157 
158 int
159 main(argc, argv)
160 	int argc;
161 	char *argv[];
162 {
163 	extern char *optarg;
164 	extern int optind;
165 	int ch, i, quit, ret;
166 	int fileflag, swapflag, ttyflag, vnodeflag;
167 	char buf[_POSIX2_LINE_MAX];
168 
169 	fileflag = swapflag = ttyflag = vnodeflag = 0;
170 	while ((ch = getopt(argc, argv, "TM:N:fiknstv")) != -1)
171 		switch (ch) {
172 		case 'f':
173 			fileflag = 1;
174 			break;
175 		case 'M':
176 			memf = optarg;
177 			break;
178 		case 'N':
179 			nlistf = optarg;
180 			break;
181 		case 'n':
182 			usenumflag = 1;
183 			break;
184 		case 's':
185 			swapflag = 1;
186 			break;
187 		case 'T':
188 			totalflag = 1;
189 			break;
190 		case 't':
191 			ttyflag = 1;
192 			break;
193 		case 'k':
194 			kflag = 1;
195 			break;
196 		case 'v':
197 		case 'i':		/* Backward compatibility. */
198 			vnodeflag = 1;
199 			break;
200 		default:
201 			usage();
202 		}
203 	argc -= optind;
204 	argv += optind;
205 
206 	/*
207 	 * Discard setgid privileges if not the running kernel so that bad
208 	 * guys can't print interesting stuff from kernel memory.
209 	 */
210 	if (nlistf != NULL || memf != NULL)
211 		(void)setgid(getgid());
212 
213 	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, buf)) == 0)
214 		errx(1, "kvm_openfiles: %s", buf);
215 	if ((ret = kvm_nlist(kd, nl)) != 0) {
216 		if (ret == -1)
217 			errx(1, "kvm_nlist: %s", kvm_geterr(kd));
218 		for (i = quit = 0; i <= NLMANDATORY; i++)
219 			if (!nl[i].n_value) {
220 				quit = 1;
221 				warnx("undefined symbol: %s", nl[i].n_name);
222 			}
223 		if (quit)
224 			exit(1);
225 	}
226 	if (!(fileflag | vnodeflag | ttyflag | swapflag | totalflag))
227 		usage();
228 	if (fileflag || totalflag)
229 		filemode();
230 	if (vnodeflag || totalflag)
231 		vnodemode();
232 	if (ttyflag)
233 		ttymode();
234 	if (swapflag || totalflag)
235 		swapmode();
236 	exit (0);
237 }
238 
239 struct e_vnode {
240 	struct vnode *avnode;
241 	struct vnode vnode;
242 };
243 
244 void
245 vnodemode()
246 {
247 	register struct e_vnode *e_vnodebase, *endvnode, *evp;
248 	register struct vnode *vp;
249 	register struct mount *maddr, *mp;
250 	int numvnodes;
251 
252 	e_vnodebase = loadvnodes(&numvnodes);
253 	if (totalflag) {
254 		(void)printf("%7d vnodes\n", numvnodes);
255 		return;
256 	}
257 	endvnode = e_vnodebase + numvnodes;
258 	(void)printf("%d active vnodes\n", numvnodes);
259 
260 
261 #define ST	mp->mnt_stat
262 	maddr = NULL;
263 	for (evp = e_vnodebase; evp < endvnode; evp++) {
264 		vp = &evp->vnode;
265 		if (vp->v_mount != maddr) {
266 			/*
267 			 * New filesystem
268 			 */
269 			if ((mp = getmnt(vp->v_mount)) == NULL)
270 				continue;
271 			maddr = vp->v_mount;
272 			mount_print(mp);
273 			vnode_header();
274 			if (!strncmp(ST.f_fstypename, MOUNT_FFS, MFSNAMELEN) ||
275 			    !strncmp(ST.f_fstypename, MOUNT_MFS, MFSNAMELEN)) {
276 				ufs_header();
277 			} else if (!strncmp(ST.f_fstypename, MOUNT_NFS,
278 			    MFSNAMELEN)) {
279 				nfs_header();
280 			}
281 			(void)printf("\n");
282 		}
283 		vnode_print(evp->avnode, vp);
284 		if (!strncmp(ST.f_fstypename, MOUNT_FFS, MFSNAMELEN) ||
285 		    !strncmp(ST.f_fstypename, MOUNT_MFS, MFSNAMELEN)) {
286 			ufs_print(vp);
287 		} else if (!strncmp(ST.f_fstypename, MOUNT_NFS, MFSNAMELEN)) {
288 			nfs_print(vp);
289 		}
290 		(void)printf("\n");
291 	}
292 	free(e_vnodebase);
293 }
294 
295 void
296 vnode_header()
297 {
298 	(void)printf("ADDR     TYP VFLAG  USE HOLD");
299 }
300 
301 void
302 vnode_print(avnode, vp)
303 	struct vnode *avnode;
304 	struct vnode *vp;
305 {
306 	char *type, flags[16];
307 	char *fp = flags;
308 	register int flag;
309 
310 	/*
311 	 * set type
312 	 */
313 	switch(vp->v_type) {
314 	case VNON:
315 		type = "non"; break;
316 	case VREG:
317 		type = "reg"; break;
318 	case VDIR:
319 		type = "dir"; break;
320 	case VBLK:
321 		type = "blk"; break;
322 	case VCHR:
323 		type = "chr"; break;
324 	case VLNK:
325 		type = "lnk"; break;
326 	case VSOCK:
327 		type = "soc"; break;
328 	case VFIFO:
329 		type = "fif"; break;
330 	case VBAD:
331 		type = "bad"; break;
332 	default:
333 		type = "unk"; break;
334 	}
335 	/*
336 	 * gather flags
337 	 */
338 	flag = vp->v_flag;
339 	if (flag & VROOT)
340 		*fp++ = 'R';
341 	if (flag & VTEXT)
342 		*fp++ = 'T';
343 	if (flag & VSYSTEM)
344 		*fp++ = 'S';
345 	if (flag & VISTTY)
346 		*fp++ = 'I';
347 	if (flag & VXLOCK)
348 		*fp++ = 'L';
349 	if (flag & VXWANT)
350 		*fp++ = 'W';
351 	if (flag & VBWAIT)
352 		*fp++ = 'B';
353 	if (flag & VALIASED)
354 		*fp++ = 'A';
355 	if (flag == 0)
356 		*fp++ = '-';
357 	*fp = '\0';
358 	(void)printf("%8x %s %5s %4d %4d",
359 	    avnode, type, flags, vp->v_usecount, vp->v_holdcnt);
360 }
361 
362 void
363 ufs_header()
364 {
365 	(void)printf(" FILEID IFLAG RDEV|SZ");
366 }
367 
368 int
369 ufs_print(vp)
370 	struct vnode *vp;
371 {
372 	register int flag;
373 	struct inode inode, *ip = &inode;
374 	char flagbuf[16], *flags = flagbuf;
375 	char *name;
376 	mode_t type;
377 
378 	KGETRET(VTOI(vp), &inode, sizeof(struct inode), "vnode's inode");
379 	flag = ip->i_flag;
380 	if (flag & IN_LOCKED)
381 		*flags++ = 'L';
382 	if (flag & IN_WANTED)
383 		*flags++ = 'W';
384 	if (flag & IN_RENAME)
385 		*flags++ = 'R';
386 	if (flag & IN_UPDATE)
387 		*flags++ = 'U';
388 	if (flag & IN_ACCESS)
389 		*flags++ = 'A';
390 	if (flag & IN_CHANGE)
391 		*flags++ = 'C';
392 	if (flag & IN_MODIFIED)
393 		*flags++ = 'M';
394 	if (flag & IN_SHLOCK)
395 		*flags++ = 'S';
396 	if (flag & IN_EXLOCK)
397 		*flags++ = 'E';
398 	if (flag & IN_LWAIT)
399 		*flags++ = 'Z';
400 	if (flag == 0)
401 		*flags++ = '-';
402 	*flags = '\0';
403 
404 	(void)printf(" %6d %5s", ip->i_number, flagbuf);
405 	type = ip->i_mode & S_IFMT;
406 	if (S_ISCHR(ip->i_mode) || S_ISBLK(ip->i_mode))
407 		if (usenumflag || ((name = devname(ip->i_rdev, type)) == NULL))
408 			(void)printf("   %2d,%-2d",
409 			    major(ip->i_rdev), minor(ip->i_rdev));
410 		else
411 			(void)printf(" %7s", name);
412 	else
413 		(void)printf(" %7qd", ip->i_size);
414 	return (0);
415 }
416 
417 void
418 nfs_header()
419 {
420 	(void)printf(" FILEID NFLAG RDEV|SZ");
421 }
422 
423 int
424 nfs_print(vp)
425 	struct vnode *vp;
426 {
427 	struct nfsnode nfsnode, *np = &nfsnode;
428 	char flagbuf[16], *flags = flagbuf;
429 	register int flag;
430 	char *name;
431 	mode_t type;
432 
433 	KGETRET(VTONFS(vp), &nfsnode, sizeof(nfsnode), "vnode's nfsnode");
434 	flag = np->n_flag;
435 	if (flag & NFLUSHWANT)
436 		*flags++ = 'W';
437 	if (flag & NFLUSHINPROG)
438 		*flags++ = 'P';
439 	if (flag & NMODIFIED)
440 		*flags++ = 'M';
441 	if (flag & NWRITEERR)
442 		*flags++ = 'E';
443 	if (flag & NQNFSNONCACHE)
444 		*flags++ = 'X';
445 	if (flag & NQNFSWRITE)
446 		*flags++ = 'O';
447 	if (flag & NQNFSEVICTED)
448 		*flags++ = 'G';
449 	if (flag == 0)
450 		*flags++ = '-';
451 	*flags = '\0';
452 
453 #define VT	np->n_vattr
454 	(void)printf(" %6d %5s", VT.va_fileid, flagbuf);
455 	type = VT.va_mode & S_IFMT;
456 	if (S_ISCHR(VT.va_mode) || S_ISBLK(VT.va_mode))
457 		if (usenumflag || ((name = devname(VT.va_rdev, type)) == NULL))
458 			(void)printf("   %2d,%-2d",
459 			    major(VT.va_rdev), minor(VT.va_rdev));
460 		else
461 			(void)printf(" %7s", name);
462 	else
463 		(void)printf(" %7qd", np->n_size);
464 	return (0);
465 }
466 
467 /*
468  * Given a pointer to a mount structure in kernel space,
469  * read it in and return a usable pointer to it.
470  */
471 struct mount *
472 getmnt(maddr)
473 	struct mount *maddr;
474 {
475 	static struct mtab {
476 		struct mtab *next;
477 		struct mount *maddr;
478 		struct mount mount;
479 	} *mhead = NULL;
480 	register struct mtab *mt;
481 
482 	for (mt = mhead; mt != NULL; mt = mt->next)
483 		if (maddr == mt->maddr)
484 			return (&mt->mount);
485 	if ((mt = malloc(sizeof(struct mtab))) == NULL)
486 		err(1, NULL);
487 	KGETRET(maddr, &mt->mount, sizeof(struct mount), "mount table");
488 	mt->maddr = maddr;
489 	mt->next = mhead;
490 	mhead = mt;
491 	return (&mt->mount);
492 }
493 
494 void
495 mount_print(mp)
496 	struct mount *mp;
497 {
498 	register int flags;
499 	char *type;
500 
501 #define ST	mp->mnt_stat
502 	(void)printf("*** MOUNT ");
503 	(void)printf("%.*s %s on %s", MFSNAMELEN, ST.f_fstypename,
504 	    ST.f_mntfromname, ST.f_mntonname);
505 	if (flags = mp->mnt_flag) {
506 		char *comma = "(";
507 
508 		putchar(' ');
509 		/* user visable flags */
510 		if (flags & MNT_RDONLY) {
511 			(void)printf("%srdonly", comma);
512 			flags &= ~MNT_RDONLY;
513 			comma = ",";
514 		}
515 		if (flags & MNT_SYNCHRONOUS) {
516 			(void)printf("%ssynchronous", comma);
517 			flags &= ~MNT_SYNCHRONOUS;
518 			comma = ",";
519 		}
520 		if (flags & MNT_NOEXEC) {
521 			(void)printf("%snoexec", comma);
522 			flags &= ~MNT_NOEXEC;
523 			comma = ",";
524 		}
525 		if (flags & MNT_NOSUID) {
526 			(void)printf("%snosuid", comma);
527 			flags &= ~MNT_NOSUID;
528 			comma = ",";
529 		}
530 		if (flags & MNT_NODEV) {
531 			(void)printf("%snodev", comma);
532 			flags &= ~MNT_NODEV;
533 			comma = ",";
534 		}
535 		if (flags & MNT_UNION) {
536 			(void)printf("%sunion", comma);
537 			flags &= ~MNT_UNION;
538 			comma = ",";
539 		}
540 		if (flags & MNT_ASYNC) {
541 			(void)printf("%sasync", comma);
542 			flags &= ~MNT_ASYNC;
543 			comma = ",";
544 		}
545 		if (flags & MNT_NOCOREDUMP) {
546 			(void)printf("%snocoredump", comma);
547 			flags &= ~MNT_NOCOREDUMP;
548 			comma = ",";
549 		}
550 		if (flags & MNT_EXRDONLY) {
551 			(void)printf("%sexrdonly", comma);
552 			flags &= ~MNT_EXRDONLY;
553 			comma = ",";
554 		}
555 		if (flags & MNT_EXPORTED) {
556 			(void)printf("%sexport", comma);
557 			flags &= ~MNT_EXPORTED;
558 			comma = ",";
559 		}
560 		if (flags & MNT_DEFEXPORTED) {
561 			(void)printf("%sdefdexported", comma);
562 			flags &= ~MNT_DEFEXPORTED;
563 			comma = ",";
564 		}
565 		if (flags & MNT_EXPORTANON) {
566 			(void)printf("%sexportanon", comma);
567 			flags &= ~MNT_EXPORTANON;
568 			comma = ",";
569 		}
570 		if (flags & MNT_EXKERB) {
571 			(void)printf("%sexkerb", comma);
572 			flags &= ~MNT_EXKERB;
573 			comma = ",";
574 		}
575 		if (flags & MNT_LOCAL) {
576 			(void)printf("%slocal", comma);
577 			flags &= ~MNT_LOCAL;
578 			comma = ",";
579 		}
580 		if (flags & MNT_QUOTA) {
581 			(void)printf("%squota", comma);
582 			flags &= ~MNT_QUOTA;
583 			comma = ",";
584 		}
585 		if (flags & MNT_ROOTFS) {
586 			(void)printf("%srootfs", comma);
587 			flags &= ~MNT_ROOTFS;
588 			comma = ",";
589 		}
590 		/* filesystem control flags */
591 		if (flags & MNT_UPDATE) {
592 			(void)printf("%supdate", comma);
593 			flags &= ~MNT_UPDATE;
594 			comma = ",";
595 		}
596 		if (flags & MNT_MLOCK) {
597 			(void)printf("%slock", comma);
598 			flags &= ~MNT_MLOCK;
599 			comma = ",";
600 		}
601 		if (flags & MNT_MWAIT) {
602 			(void)printf("%swait", comma);
603 			flags &= ~MNT_MWAIT;
604 			comma = ",";
605 		}
606 		if (flags & MNT_MPBUSY) {
607 			(void)printf("%sbusy", comma);
608 			flags &= ~MNT_MPBUSY;
609 			comma = ",";
610 		}
611 		if (flags & MNT_MPWANT) {
612 			(void)printf("%swant", comma);
613 			flags &= ~MNT_MPWANT;
614 			comma = ",";
615 		}
616 		if (flags & MNT_UNMOUNT) {
617 			(void)printf("%sunmount", comma);
618 			flags &= ~MNT_UNMOUNT;
619 			comma = ",";
620 		}
621 		if (flags)
622 			(void)printf("%sunknown_flags:%x", comma, flags);
623 		(void)printf(")");
624 	}
625 	(void)printf("\n");
626 #undef ST
627 }
628 
629 struct e_vnode *
630 loadvnodes(avnodes)
631 	int *avnodes;
632 {
633 	int mib[2];
634 	size_t copysize;
635 	struct e_vnode *vnodebase;
636 
637 	if (memf != NULL) {
638 		/*
639 		 * do it by hand
640 		 */
641 		return (kinfo_vnodes(avnodes));
642 	}
643 	mib[0] = CTL_KERN;
644 	mib[1] = KERN_VNODE;
645 	if (sysctl(mib, 2, NULL, &copysize, NULL, 0) == -1)
646 		err(1, "sysctl: KERN_VNODE");
647 	if ((vnodebase = malloc(copysize)) == NULL)
648 		err(1, NULL);
649 	if (sysctl(mib, 2, vnodebase, &copysize, NULL, 0) == -1)
650 		err(1, "sysctl: KERN_VNODE");
651 	if (copysize % sizeof(struct e_vnode))
652 		errx(1, "vnode size mismatch");
653 	*avnodes = copysize / sizeof(struct e_vnode);
654 
655 	return (vnodebase);
656 }
657 
658 /*
659  * simulate what a running kernel does in in kinfo_vnode
660  */
661 struct e_vnode *
662 kinfo_vnodes(avnodes)
663 	int *avnodes;
664 {
665 	struct mntlist mountlist;
666 	struct mount *mp, mount;
667 	struct vnode *vp, vnode;
668 	char *vbuf, *evbuf, *bp;
669 	int num, numvnodes;
670 
671 #define VPTRSZ  sizeof(struct vnode *)
672 #define VNODESZ sizeof(struct vnode)
673 
674 	KGET(V_NUMV, numvnodes);
675 	if ((vbuf = malloc((numvnodes + 20) * (VPTRSZ + VNODESZ))) == NULL)
676 		err(1, NULL);
677 	bp = vbuf;
678 	evbuf = vbuf + (numvnodes + 20) * (VPTRSZ + VNODESZ);
679 	KGET(V_MOUNTLIST, mountlist);
680 	for (num = 0, mp = mountlist.cqh_first; ; mp = mount.mnt_list.cqe_next) {
681 		KGET2(mp, &mount, sizeof(mount), "mount entry");
682 		for (vp = mount.mnt_vnodelist.lh_first;
683 		    vp != NULL; vp = vnode.v_mntvnodes.le_next) {
684 			KGET2(vp, &vnode, sizeof(vnode), "vnode");
685 			if ((bp + VPTRSZ + VNODESZ) > evbuf)
686 				/* XXX - should realloc */
687 				errx(1, "no more room for vnodes");
688 			memmove(bp, &vp, VPTRSZ);
689 			bp += VPTRSZ;
690 			memmove(bp, &vnode, VNODESZ);
691 			bp += VNODESZ;
692 			num++;
693 		}
694 		if (mp == mountlist.cqh_last)
695 			break;
696 	}
697 	*avnodes = num;
698 	return ((struct e_vnode *)vbuf);
699 }
700 
701 char hdr[]="  LINE  RAW  CAN  OUT  HWT LWT    COL STATE      SESS  PGID DISC\n";
702 
703 void
704 ttymode()
705 {
706 	int ntty, i;
707 	struct ttylist_head tty_head;
708 	struct tty *tp, tty;
709 
710 	KGET(TTY_NTTY, ntty);
711 	(void)printf("%d terminal device%s\n", ntty, ntty == 1 ? "" : "s");
712 	KGET(TTY_TTYLIST, tty_head);
713 	(void)printf(hdr);
714 	for (tp = tty_head.tqh_first; tp; tp = tty.tty_link.tqe_next) {
715 		KGET2(tp, &tty, sizeof tty, "tty struct");
716 		ttyprt(&tty);
717 	}
718 }
719 
720 struct {
721 	int flag;
722 	char val;
723 } ttystates[] = {
724 	{ TS_WOPEN,	'W'},
725 	{ TS_ISOPEN,	'O'},
726 	{ TS_CARR_ON,	'C'},
727 	{ TS_TIMEOUT,	'T'},
728 	{ TS_FLUSH,	'F'},
729 	{ TS_BUSY,	'B'},
730 	{ TS_ASLEEP,	'A'},
731 	{ TS_XCLUDE,	'X'},
732 	{ TS_TTSTOP,	'S'},
733 	{ TS_TBLOCK,	'K'},
734 	{ TS_ASYNC,	'Y'},
735 	{ TS_BKSL,	'D'},
736 	{ TS_ERASE,	'E'},
737 	{ TS_LNCH,	'L'},
738 	{ TS_TYPEN,	'P'},
739 	{ TS_CNTTB,	'N'},
740 	{ 0,	       '\0'},
741 };
742 
743 void
744 ttyprt(tp)
745 	register struct tty *tp;
746 {
747 	register int i, j;
748 	pid_t pgid;
749 	char *name, state[20];
750 
751 	if (usenumflag || (name = devname(tp->t_dev, S_IFCHR)) == NULL)
752 		(void)printf("0x%3x:%1x ", major(tp->t_dev), minor(tp->t_dev));
753 	else
754 		(void)printf("%-7s ", name);
755 	(void)printf("%3d %4d ", tp->t_rawq.c_cc, tp->t_canq.c_cc);
756 	(void)printf("%4d %4d %3d %6d ", tp->t_outq.c_cc,
757 		tp->t_hiwat, tp->t_lowat, tp->t_column);
758 	for (i = j = 0; ttystates[i].flag; i++)
759 		if (tp->t_state&ttystates[i].flag)
760 			state[j++] = ttystates[i].val;
761 	if (j == 0)
762 		state[j++] = '-';
763 	state[j] = '\0';
764 	(void)printf("%-6s %8x", state, (u_long)tp->t_session & ~KERNBASE);
765 	pgid = 0;
766 	if (tp->t_pgrp != NULL)
767 		KGET2(&tp->t_pgrp->pg_id, &pgid, sizeof(pid_t), "pgid");
768 	(void)printf("%6d ", pgid);
769 	switch (tp->t_line) {
770 	case TTYDISC:
771 		(void)printf("term\n");
772 		break;
773 	case TABLDISC:
774 		(void)printf("tab\n");
775 		break;
776 	case SLIPDISC:
777 		(void)printf("slip\n");
778 		break;
779 	case PPPDISC:
780 		(void)printf("ppp\n");
781 		break;
782 	case STRIPDISC:
783 		(void)printf("strip\n");
784 		break;
785 	default:
786 		(void)printf("%d\n", tp->t_line);
787 		break;
788 	}
789 }
790 
791 void
792 filemode()
793 {
794 	register struct file *fp;
795 	struct file *addr;
796 	char *buf, flagbuf[16], *fbp;
797 	int len, maxfile, nfile;
798 	static char *dtypes[] = { "???", "inode", "socket" };
799 
800 	KGET(FNL_MAXFILE, maxfile);
801 	if (totalflag) {
802 		KGET(FNL_NFILE, nfile);
803 		(void)printf("%3d/%3d files\n", nfile, maxfile);
804 		return;
805 	}
806 	if (getfiles(&buf, &len) == -1)
807 		return;
808 	/*
809 	 * Getfiles returns in malloc'd memory a pointer to the first file
810 	 * structure, and then an array of file structs (whose addresses are
811 	 * derivable from the previous entry).
812 	 */
813 	addr = ((struct filelist *)buf)->lh_first;
814 	fp = (struct file *)(buf + sizeof(struct filelist));
815 	nfile = (len - sizeof(struct filelist)) / sizeof(struct file);
816 
817 	(void)printf("%d/%d open files\n", nfile, maxfile);
818 	(void)printf("   LOC   TYPE    FLG     CNT  MSG    DATA    OFFSET\n");
819 	for (; (char *)fp < buf + len; addr = fp->f_list.le_next, fp++) {
820 		if ((unsigned)fp->f_type > DTYPE_SOCKET)
821 			continue;
822 		(void)printf("%x ", addr);
823 		(void)printf("%-8.8s", dtypes[fp->f_type]);
824 		fbp = flagbuf;
825 		if (fp->f_flag & FREAD)
826 			*fbp++ = 'R';
827 		if (fp->f_flag & FWRITE)
828 			*fbp++ = 'W';
829 		if (fp->f_flag & FAPPEND)
830 			*fbp++ = 'A';
831 #ifdef FSHLOCK	/* currently gone */
832 		if (fp->f_flag & FSHLOCK)
833 			*fbp++ = 'S';
834 		if (fp->f_flag & FEXLOCK)
835 			*fbp++ = 'X';
836 #endif
837 		if (fp->f_flag & FASYNC)
838 			*fbp++ = 'I';
839 		*fbp = '\0';
840 		(void)printf("%6s  %3d", flagbuf, fp->f_count);
841 		(void)printf("  %3d", fp->f_msgcount);
842 		(void)printf("  %8.1x", fp->f_data);
843 		if (fp->f_offset < 0)
844 			(void)printf("  %qx\n", fp->f_offset);
845 		else
846 			(void)printf("  %qd\n", fp->f_offset);
847 	}
848 	free(buf);
849 }
850 
851 int
852 getfiles(abuf, alen)
853 	char **abuf;
854 	int *alen;
855 {
856 	size_t len;
857 	int mib[2];
858 	char *buf;
859 
860 	/*
861 	 * XXX
862 	 * Add emulation of KINFO_FILE here.
863 	 */
864 	if (memf != NULL)
865 		errx(1, "files on dead kernel, not implemented\n");
866 
867 	mib[0] = CTL_KERN;
868 	mib[1] = KERN_FILE;
869 	if (sysctl(mib, 2, NULL, &len, NULL, 0) == -1) {
870 		warn("sysctl: KERN_FILE");
871 		return (-1);
872 	}
873 	if ((buf = malloc(len)) == NULL)
874 		err(1, NULL);
875 	if (sysctl(mib, 2, buf, &len, NULL, 0) == -1) {
876 		warn("sysctl: KERN_FILE");
877 		return (-1);
878 	}
879 	*abuf = buf;
880 	*alen = len;
881 	return (0);
882 }
883 
884 /*
885  * swapmode is based on a program called swapinfo written
886  * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
887  */
888 void
889 swapmode()
890 {
891 	char *header;
892 	int hlen, nswap, nswdev, dmmax, nswapmap, niswap, niswdev;
893 	int s, e, div, i, l, avail, nfree, npfree, used;
894 	struct swdevt *sw;
895 	long blocksize, *perdev;
896 	struct map *swapmap, *kswapmap;
897 	struct mapent *mp;
898 
899 	KGET(VM_NSWAP, nswap);
900 	KGET(VM_NSWDEV, nswdev);
901 	KGET(VM_DMMAX, dmmax);
902 	KGET(VM_NSWAPMAP, nswapmap);
903 	KGET(VM_SWAPMAP, kswapmap);	/* kernel `swapmap' is a pointer */
904 	if ((sw = malloc(nswdev * sizeof(*sw))) == NULL ||
905 	    (perdev = malloc(nswdev * sizeof(*perdev))) == NULL ||
906 	    (mp = malloc(nswapmap * sizeof(*mp))) == NULL)
907 		err(1, "malloc");
908 	KGET1(VM_SWDEVT, sw, nswdev * sizeof(*sw), "swdevt");
909 	KGET2((long)kswapmap, mp, nswapmap * sizeof(*mp), "swapmap");
910 
911 	/* Supports sequential swap */
912 	if (nl[VM_NISWAP].n_value != 0) {
913 		KGET(VM_NISWAP, niswap);
914 		KGET(VM_NISWDEV, niswdev);
915 	} else {
916 		niswap = nswap;
917 		niswdev = nswdev;
918 	}
919 
920 	/* First entry in map is `struct map'; rest are mapent's. */
921 	swapmap = (struct map *)mp;
922 	if (nswapmap != swapmap->m_limit - (struct mapent *)kswapmap)
923 		errx(1, "panic: nswapmap goof");
924 
925 	/* Count up swap space. */
926 	nfree = 0;
927 	memset(perdev, 0, nswdev * sizeof(*perdev));
928 	for (mp++; mp->m_addr != 0; mp++) {
929 		s = mp->m_addr;			/* start of swap region */
930 		e = mp->m_addr + mp->m_size;	/* end of region */
931 		nfree += mp->m_size;
932 
933 		/*
934 		 * Swap space is split up among the configured disks.
935 		 *
936 		 * For interleaved swap devices, the first dmmax blocks
937 		 * of swap space some from the first disk, the next dmmax
938 		 * blocks from the next, and so on up to niswap blocks.
939 		 *
940 		 * Sequential swap devices follow the interleaved devices
941 		 * (i.e. blocks starting at niswap) in the order in which
942 		 * they appear in the swdev table.  The size of each device
943 		 * will be a multiple of dmmax.
944 		 *
945 		 * The list of free space joins adjacent free blocks,
946 		 * ignoring device boundries.  If we want to keep track
947 		 * of this information per device, we'll just have to
948 		 * extract it ourselves.  We know that dmmax-sized chunks
949 		 * cannot span device boundaries (interleaved or sequential)
950 		 * so we loop over such chunks assigning them to devices.
951 		 */
952 		i = -1;
953 		while (s < e) {		/* XXX this is inefficient */
954 			int bound = roundup(s+1, dmmax);
955 
956 			if (bound > e)
957 				bound = e;
958 			if (bound <= niswap) {
959 				/* Interleaved swap chunk. */
960 				if (i == -1)
961 					i = (s / dmmax) % niswdev;
962 				perdev[i] += bound - s;
963 				if (++i >= niswdev)
964 					i = 0;
965 			} else {
966 				/* Sequential swap chunk. */
967 				if (i < niswdev) {
968 					i = niswdev;
969 					l = niswap + sw[i].sw_nblks;
970 				}
971 				while (s >= l) {
972 					/* XXX don't die on bogus blocks */
973 					if (i == nswdev-1)
974 						break;
975 					l += sw[++i].sw_nblks;
976 				}
977 				perdev[i] += bound - s;
978 			}
979 			s = bound;
980 		}
981 	}
982 
983 	if (kflag) {
984 		header = "1K-blocks";
985 		blocksize = 1024;
986 		hlen = strlen(header);
987 	} else
988 		header = getbsize(&hlen, &blocksize);
989 	if (!totalflag)
990 		(void)printf("%-11s %*s %8s %8s %8s  %s\n",
991 		    "Device", hlen, header,
992 		    "Used", "Avail", "Capacity", "Type");
993 	div = blocksize / 512;
994 	avail = npfree = 0;
995 	for (i = 0; i < nswdev; i++) {
996 		int xsize, xfree;
997 
998 		/*
999 		 * Don't report statistics for partitions which have not
1000 		 * yet been activated via swapon(8).
1001 		 */
1002 		if (!(sw[i].sw_flags & SW_FREED))
1003 			continue;
1004 
1005 		if (!totalflag)
1006 			(void)printf("/dev/%-6s %*d ",
1007 			    devname(sw[i].sw_dev, S_IFBLK),
1008 			    hlen, sw[i].sw_nblks / div);
1009 
1010 		xsize = sw[i].sw_nblks;
1011 		xfree = perdev[i];
1012 		used = xsize - xfree;
1013 		npfree++;
1014 		avail += xsize;
1015 		if (totalflag)
1016 			continue;
1017 		(void)printf("%8d %8d %5.0f%%    %s\n",
1018 		    used / div, xfree / div,
1019 		    (double)used / (double)xsize * 100.0,
1020 		    (sw[i].sw_flags & SW_SEQUENTIAL) ?
1021 			     "Sequential" : "Interleaved");
1022 	}
1023 
1024 	/*
1025 	 * If only one partition has been set up via swapon(8), we don't
1026 	 * need to bother with totals.
1027 	 */
1028 	used = avail - nfree;
1029 	if (totalflag) {
1030 		(void)printf("%dM/%dM swap space\n", used / 2048, avail / 2048);
1031 		return;
1032 	}
1033 	if (npfree > 1) {
1034 		(void)printf("%-11s %*d %8d %8d %5.0f%%\n",
1035 		    "Total", hlen, avail / div, used / div, nfree / div,
1036 		    (double)used / (double)avail * 100.0);
1037 	}
1038 }
1039 
1040 void
1041 usage()
1042 {
1043 	(void)fprintf(stderr,
1044 	    "usage: pstat [-Tfknstv] [-M core] [-N system]\n");
1045 	exit(1);
1046 }
1047