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