xref: /netbsd-src/usr.sbin/pstat/pstat.c (revision 81b108b45f75f89f1e3ffad9fb6f074e771c0935)
1 /*	$NetBSD: pstat.c,v 1.25 1996/06/03 19:00:23 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.25 1996/06/03 19:00:23 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_EXPORTED) {
536 			(void)printf("%sexport", comma);
537 			flags &= ~MNT_EXPORTED;
538 			comma = ",";
539 		}
540 		if (flags & MNT_EXRDONLY) {
541 			(void)printf("%sexrdonly", comma);
542 			flags &= ~MNT_EXRDONLY;
543 			comma = ",";
544 		}
545 		if (flags & MNT_LOCAL) {
546 			(void)printf("%slocal", comma);
547 			flags &= ~MNT_LOCAL;
548 			comma = ",";
549 		}
550 		if (flags & MNT_QUOTA) {
551 			(void)printf("%squota", comma);
552 			flags &= ~MNT_QUOTA;
553 			comma = ",";
554 		}
555 		if (flags & MNT_ROOTFS) {
556 			(void)printf("%srootfs", comma);
557 			flags &= ~MNT_ROOTFS;
558 			comma = ",";
559 		}
560 		/* filesystem control flags */
561 		if (flags & MNT_UPDATE) {
562 			(void)printf("%supdate", comma);
563 			flags &= ~MNT_UPDATE;
564 			comma = ",";
565 		}
566 		if (flags & MNT_MLOCK) {
567 			(void)printf("%slock", comma);
568 			flags &= ~MNT_MLOCK;
569 			comma = ",";
570 		}
571 		if (flags & MNT_MWAIT) {
572 			(void)printf("%swait", comma);
573 			flags &= ~MNT_MWAIT;
574 			comma = ",";
575 		}
576 		if (flags & MNT_MPBUSY) {
577 			(void)printf("%sbusy", comma);
578 			flags &= ~MNT_MPBUSY;
579 			comma = ",";
580 		}
581 		if (flags & MNT_MPWANT) {
582 			(void)printf("%swant", comma);
583 			flags &= ~MNT_MPWANT;
584 			comma = ",";
585 		}
586 		if (flags & MNT_UNMOUNT) {
587 			(void)printf("%sunmount", comma);
588 			flags &= ~MNT_UNMOUNT;
589 			comma = ",";
590 		}
591 		if (flags)
592 			(void)printf("%sunknown_flags:%x", comma, flags);
593 		(void)printf(")");
594 	}
595 	(void)printf("\n");
596 #undef ST
597 }
598 
599 struct e_vnode *
600 loadvnodes(avnodes)
601 	int *avnodes;
602 {
603 	int mib[2];
604 	size_t copysize;
605 	struct e_vnode *vnodebase;
606 
607 	if (memf != NULL) {
608 		/*
609 		 * do it by hand
610 		 */
611 		return (kinfo_vnodes(avnodes));
612 	}
613 	mib[0] = CTL_KERN;
614 	mib[1] = KERN_VNODE;
615 	if (sysctl(mib, 2, NULL, &copysize, NULL, 0) == -1)
616 		err(1, "sysctl: KERN_VNODE");
617 	if ((vnodebase = malloc(copysize)) == NULL)
618 		err(1, NULL);
619 	if (sysctl(mib, 2, vnodebase, &copysize, NULL, 0) == -1)
620 		err(1, "sysctl: KERN_VNODE");
621 	if (copysize % sizeof(struct e_vnode))
622 		errx(1, "vnode size mismatch");
623 	*avnodes = copysize / sizeof(struct e_vnode);
624 
625 	return (vnodebase);
626 }
627 
628 /*
629  * simulate what a running kernel does in in kinfo_vnode
630  */
631 struct e_vnode *
632 kinfo_vnodes(avnodes)
633 	int *avnodes;
634 {
635 	struct mntlist mountlist;
636 	struct mount *mp, mount;
637 	struct vnode *vp, vnode;
638 	char *vbuf, *evbuf, *bp;
639 	int num, numvnodes;
640 
641 #define VPTRSZ  sizeof(struct vnode *)
642 #define VNODESZ sizeof(struct vnode)
643 
644 	KGET(V_NUMV, numvnodes);
645 	if ((vbuf = malloc((numvnodes + 20) * (VPTRSZ + VNODESZ))) == NULL)
646 		err(1, NULL);
647 	bp = vbuf;
648 	evbuf = vbuf + (numvnodes + 20) * (VPTRSZ + VNODESZ);
649 	KGET(V_MOUNTLIST, mountlist);
650 	for (num = 0, mp = mountlist.cqh_first; ; mp = mount.mnt_list.cqe_next) {
651 		KGET2(mp, &mount, sizeof(mount), "mount entry");
652 		for (vp = mount.mnt_vnodelist.lh_first;
653 		    vp != NULL; vp = vnode.v_mntvnodes.le_next) {
654 			KGET2(vp, &vnode, sizeof(vnode), "vnode");
655 			if ((bp + VPTRSZ + VNODESZ) > evbuf)
656 				/* XXX - should realloc */
657 				errx(1, "no more room for vnodes");
658 			memmove(bp, &vp, VPTRSZ);
659 			bp += VPTRSZ;
660 			memmove(bp, &vnode, VNODESZ);
661 			bp += VNODESZ;
662 			num++;
663 		}
664 		if (mp == mountlist.cqh_last)
665 			break;
666 	}
667 	*avnodes = num;
668 	return ((struct e_vnode *)vbuf);
669 }
670 
671 char hdr[]="  LINE  RAW  CAN  OUT  HWT LWT    COL STATE      SESS  PGID DISC\n";
672 
673 void
674 ttymode()
675 {
676 	int ntty, i;
677 	struct ttylist_head tty_head;
678 	struct tty *tp, tty;
679 
680 	KGET(TTY_NTTY, ntty);
681 	(void)printf("%d terminal device%s\n", ntty, ntty == 1 ? "" : "s");
682 	KGET(TTY_TTYLIST, tty_head);
683 	(void)printf(hdr);
684 	for (tp = tty_head.tqh_first; tp; tp = tty.tty_link.tqe_next) {
685 		KGET2(tp, &tty, sizeof tty, "tty struct");
686 		ttyprt(&tty);
687 	}
688 }
689 
690 struct {
691 	int flag;
692 	char val;
693 } ttystates[] = {
694 	{ TS_WOPEN,	'W'},
695 	{ TS_ISOPEN,	'O'},
696 	{ TS_CARR_ON,	'C'},
697 	{ TS_TIMEOUT,	'T'},
698 	{ TS_FLUSH,	'F'},
699 	{ TS_BUSY,	'B'},
700 	{ TS_ASLEEP,	'A'},
701 	{ TS_XCLUDE,	'X'},
702 	{ TS_TTSTOP,	'S'},
703 	{ TS_TBLOCK,	'K'},
704 	{ TS_ASYNC,	'Y'},
705 	{ TS_BKSL,	'D'},
706 	{ TS_ERASE,	'E'},
707 	{ TS_LNCH,	'L'},
708 	{ TS_TYPEN,	'P'},
709 	{ TS_CNTTB,	'N'},
710 	{ 0,	       '\0'},
711 };
712 
713 void
714 ttyprt(tp)
715 	register struct tty *tp;
716 {
717 	register int i, j;
718 	pid_t pgid;
719 	char *name, state[20];
720 
721 	if (usenumflag || (name = devname(tp->t_dev, S_IFCHR)) == NULL)
722 		(void)printf("0x%3x:%1x ", major(tp->t_dev), minor(tp->t_dev));
723 	else
724 		(void)printf("%-7s ", name);
725 	(void)printf("%3d %4d ", tp->t_rawq.c_cc, tp->t_canq.c_cc);
726 	(void)printf("%4d %4d %3d %6d ", tp->t_outq.c_cc,
727 		tp->t_hiwat, tp->t_lowat, tp->t_column);
728 	for (i = j = 0; ttystates[i].flag; i++)
729 		if (tp->t_state&ttystates[i].flag)
730 			state[j++] = ttystates[i].val;
731 	if (j == 0)
732 		state[j++] = '-';
733 	state[j] = '\0';
734 	(void)printf("%-6s %8x", state, (u_long)tp->t_session & ~KERNBASE);
735 	pgid = 0;
736 	if (tp->t_pgrp != NULL)
737 		KGET2(&tp->t_pgrp->pg_id, &pgid, sizeof(pid_t), "pgid");
738 	(void)printf("%6d ", pgid);
739 	switch (tp->t_line) {
740 	case TTYDISC:
741 		(void)printf("term\n");
742 		break;
743 	case TABLDISC:
744 		(void)printf("tab\n");
745 		break;
746 	case SLIPDISC:
747 		(void)printf("slip\n");
748 		break;
749 	case PPPDISC:
750 		(void)printf("ppp\n");
751 		break;
752 	case STRIPDISC:
753 		(void)printf("strip\n");
754 		break;
755 	default:
756 		(void)printf("%d\n", tp->t_line);
757 		break;
758 	}
759 }
760 
761 void
762 filemode()
763 {
764 	register struct file *fp;
765 	struct file *addr;
766 	char *buf, flagbuf[16], *fbp;
767 	int len, maxfile, nfile;
768 	static char *dtypes[] = { "???", "inode", "socket" };
769 
770 	KGET(FNL_MAXFILE, maxfile);
771 	if (totalflag) {
772 		KGET(FNL_NFILE, nfile);
773 		(void)printf("%3d/%3d files\n", nfile, maxfile);
774 		return;
775 	}
776 	if (getfiles(&buf, &len) == -1)
777 		return;
778 	/*
779 	 * Getfiles returns in malloc'd memory a pointer to the first file
780 	 * structure, and then an array of file structs (whose addresses are
781 	 * derivable from the previous entry).
782 	 */
783 	addr = ((struct filelist *)buf)->lh_first;
784 	fp = (struct file *)(buf + sizeof(struct filelist));
785 	nfile = (len - sizeof(struct filelist)) / sizeof(struct file);
786 
787 	(void)printf("%d/%d open files\n", nfile, maxfile);
788 	(void)printf("   LOC   TYPE    FLG     CNT  MSG    DATA    OFFSET\n");
789 	for (; (char *)fp < buf + len; addr = fp->f_list.le_next, fp++) {
790 		if ((unsigned)fp->f_type > DTYPE_SOCKET)
791 			continue;
792 		(void)printf("%x ", addr);
793 		(void)printf("%-8.8s", dtypes[fp->f_type]);
794 		fbp = flagbuf;
795 		if (fp->f_flag & FREAD)
796 			*fbp++ = 'R';
797 		if (fp->f_flag & FWRITE)
798 			*fbp++ = 'W';
799 		if (fp->f_flag & FAPPEND)
800 			*fbp++ = 'A';
801 #ifdef FSHLOCK	/* currently gone */
802 		if (fp->f_flag & FSHLOCK)
803 			*fbp++ = 'S';
804 		if (fp->f_flag & FEXLOCK)
805 			*fbp++ = 'X';
806 #endif
807 		if (fp->f_flag & FASYNC)
808 			*fbp++ = 'I';
809 		*fbp = '\0';
810 		(void)printf("%6s  %3d", flagbuf, fp->f_count);
811 		(void)printf("  %3d", fp->f_msgcount);
812 		(void)printf("  %8.1x", fp->f_data);
813 		if (fp->f_offset < 0)
814 			(void)printf("  %qx\n", fp->f_offset);
815 		else
816 			(void)printf("  %qd\n", fp->f_offset);
817 	}
818 	free(buf);
819 }
820 
821 int
822 getfiles(abuf, alen)
823 	char **abuf;
824 	int *alen;
825 {
826 	size_t len;
827 	int mib[2];
828 	char *buf;
829 
830 	/*
831 	 * XXX
832 	 * Add emulation of KINFO_FILE here.
833 	 */
834 	if (memf != NULL)
835 		errx(1, "files on dead kernel, not implemented\n");
836 
837 	mib[0] = CTL_KERN;
838 	mib[1] = KERN_FILE;
839 	if (sysctl(mib, 2, NULL, &len, NULL, 0) == -1) {
840 		warn("sysctl: KERN_FILE");
841 		return (-1);
842 	}
843 	if ((buf = malloc(len)) == NULL)
844 		err(1, NULL);
845 	if (sysctl(mib, 2, buf, &len, NULL, 0) == -1) {
846 		warn("sysctl: KERN_FILE");
847 		return (-1);
848 	}
849 	*abuf = buf;
850 	*alen = len;
851 	return (0);
852 }
853 
854 /*
855  * swapmode is based on a program called swapinfo written
856  * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
857  */
858 void
859 swapmode()
860 {
861 	char *header;
862 	int hlen, nswap, nswdev, dmmax, nswapmap, niswap, niswdev;
863 	int s, e, div, i, l, avail, nfree, npfree, used;
864 	struct swdevt *sw;
865 	long blocksize, *perdev;
866 	struct map *swapmap, *kswapmap;
867 	struct mapent *mp;
868 
869 	KGET(VM_NSWAP, nswap);
870 	KGET(VM_NSWDEV, nswdev);
871 	KGET(VM_DMMAX, dmmax);
872 	KGET(VM_NSWAPMAP, nswapmap);
873 	KGET(VM_SWAPMAP, kswapmap);	/* kernel `swapmap' is a pointer */
874 	if ((sw = malloc(nswdev * sizeof(*sw))) == NULL ||
875 	    (perdev = malloc(nswdev * sizeof(*perdev))) == NULL ||
876 	    (mp = malloc(nswapmap * sizeof(*mp))) == NULL)
877 		err(1, "malloc");
878 	KGET1(VM_SWDEVT, sw, nswdev * sizeof(*sw), "swdevt");
879 	KGET2((long)kswapmap, mp, nswapmap * sizeof(*mp), "swapmap");
880 
881 	/* Supports sequential swap */
882 	if (nl[VM_NISWAP].n_value != 0) {
883 		KGET(VM_NISWAP, niswap);
884 		KGET(VM_NISWDEV, niswdev);
885 	} else {
886 		niswap = nswap;
887 		niswdev = nswdev;
888 	}
889 
890 	/* First entry in map is `struct map'; rest are mapent's. */
891 	swapmap = (struct map *)mp;
892 	if (nswapmap != swapmap->m_limit - (struct mapent *)kswapmap)
893 		errx(1, "panic: nswapmap goof");
894 
895 	/* Count up swap space. */
896 	nfree = 0;
897 	memset(perdev, 0, nswdev * sizeof(*perdev));
898 	for (mp++; mp->m_addr != 0; mp++) {
899 		s = mp->m_addr;			/* start of swap region */
900 		e = mp->m_addr + mp->m_size;	/* end of region */
901 		nfree += mp->m_size;
902 
903 		/*
904 		 * Swap space is split up among the configured disks.
905 		 *
906 		 * For interleaved swap devices, the first dmmax blocks
907 		 * of swap space some from the first disk, the next dmmax
908 		 * blocks from the next, and so on up to niswap blocks.
909 		 *
910 		 * Sequential swap devices follow the interleaved devices
911 		 * (i.e. blocks starting at niswap) in the order in which
912 		 * they appear in the swdev table.  The size of each device
913 		 * will be a multiple of dmmax.
914 		 *
915 		 * The list of free space joins adjacent free blocks,
916 		 * ignoring device boundries.  If we want to keep track
917 		 * of this information per device, we'll just have to
918 		 * extract it ourselves.  We know that dmmax-sized chunks
919 		 * cannot span device boundaries (interleaved or sequential)
920 		 * so we loop over such chunks assigning them to devices.
921 		 */
922 		i = -1;
923 		while (s < e) {		/* XXX this is inefficient */
924 			int bound = roundup(s+1, dmmax);
925 
926 			if (bound > e)
927 				bound = e;
928 			if (bound <= niswap) {
929 				/* Interleaved swap chunk. */
930 				if (i == -1)
931 					i = (s / dmmax) % niswdev;
932 				perdev[i] += bound - s;
933 				if (++i >= niswdev)
934 					i = 0;
935 			} else {
936 				/* Sequential swap chunk. */
937 				if (i < niswdev) {
938 					i = niswdev;
939 					l = niswap + sw[i].sw_nblks;
940 				}
941 				while (s >= l) {
942 					/* XXX don't die on bogus blocks */
943 					if (i == nswdev-1)
944 						break;
945 					l += sw[++i].sw_nblks;
946 				}
947 				perdev[i] += bound - s;
948 			}
949 			s = bound;
950 		}
951 	}
952 
953 	if (kflag) {
954 		header = "1K-blocks";
955 		blocksize = 1024;
956 		hlen = strlen(header);
957 	} else
958 		header = getbsize(&hlen, &blocksize);
959 	if (!totalflag)
960 		(void)printf("%-11s %*s %8s %8s %8s  %s\n",
961 		    "Device", hlen, header,
962 		    "Used", "Avail", "Capacity", "Type");
963 	div = blocksize / 512;
964 	avail = npfree = 0;
965 	for (i = 0; i < nswdev; i++) {
966 		int xsize, xfree;
967 
968 		/*
969 		 * Don't report statistics for partitions which have not
970 		 * yet been activated via swapon(8).
971 		 */
972 		if (!(sw[i].sw_flags & SW_FREED))
973 			continue;
974 
975 		if (!totalflag)
976 			(void)printf("/dev/%-6s %*d ",
977 			    devname(sw[i].sw_dev, S_IFBLK),
978 			    hlen, sw[i].sw_nblks / div);
979 
980 		xsize = sw[i].sw_nblks;
981 		xfree = perdev[i];
982 		used = xsize - xfree;
983 		npfree++;
984 		avail += xsize;
985 		if (totalflag)
986 			continue;
987 		(void)printf("%8d %8d %5.0f%%    %s\n",
988 		    used / div, xfree / div,
989 		    (double)used / (double)xsize * 100.0,
990 		    (sw[i].sw_flags & SW_SEQUENTIAL) ?
991 			     "Sequential" : "Interleaved");
992 	}
993 
994 	/*
995 	 * If only one partition has been set up via swapon(8), we don't
996 	 * need to bother with totals.
997 	 */
998 	used = avail - nfree;
999 	if (totalflag) {
1000 		(void)printf("%dM/%dM swap space\n", used / 2048, avail / 2048);
1001 		return;
1002 	}
1003 	if (npfree > 1) {
1004 		(void)printf("%-11s %*d %8d %8d %5.0f%%\n",
1005 		    "Total", hlen, avail / div, used / div, nfree / div,
1006 		    (double)used / (double)avail * 100.0);
1007 	}
1008 }
1009 
1010 void
1011 usage()
1012 {
1013 	(void)fprintf(stderr,
1014 	    "usage: pstat [-Tfknstv] [-M core] [-N system]\n");
1015 	exit(1);
1016 }
1017