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