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