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