pstat.c revision 1.55
1/*	$OpenBSD: pstat.c,v 1.55 2005/12/17 13:56:02 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.55 2005/12/17 13:56:02 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	struct ufs1_dinode di1;
360	char flagbuf[16], *flags = flagbuf;
361	char *name;
362	mode_t type;
363
364	KGETRET(VTOI(vp), &inode, sizeof(struct inode), "vnode's inode");
365	KGETRET(inode.i_din1, &di1, sizeof(struct ufs1_dinode),
366	    "vnode's dinode");
367
368	inode.i_din1 = &di1;
369	flag = ip->i_flag;
370#if 0
371	if (flag & IN_LOCKED)
372		*flags++ = 'L';
373	if (flag & IN_WANTED)
374		*flags++ = 'W';
375	if (flag & IN_LWAIT)
376		*flags++ = 'Z';
377#endif
378	if (flag & IN_ACCESS)
379		*flags++ = 'A';
380	if (flag & IN_CHANGE)
381		*flags++ = 'C';
382	if (flag & IN_UPDATE)
383		*flags++ = 'U';
384	if (flag & IN_MODIFIED)
385		*flags++ = 'M';
386	if (flag & IN_RENAME)
387		*flags++ = 'R';
388	if (flag & IN_SHLOCK)
389		*flags++ = 'S';
390	if (flag & IN_EXLOCK)
391		*flags++ = 'E';
392	if (flag == 0)
393		*flags++ = '-';
394	*flags = '\0';
395
396	(void)printf(" %6d %5s", ip->i_number, flagbuf);
397	type = ip->i_ffs_mode & S_IFMT;
398	if (S_ISCHR(ip->i_ffs_mode) || S_ISBLK(ip->i_ffs_mode))
399		if (usenumflag ||
400		    ((name = devname(ip->i_ffs_rdev, type)) == NULL))
401			(void)printf("   %2d,%-2d",
402			    major(ip->i_ffs_rdev), minor(ip->i_ffs_rdev));
403		else
404			(void)printf(" %7s", name);
405	else
406		(void)printf(" %7qd", ip->i_ffs_size);
407	return (0);
408}
409
410void
411ext2fs_header(void)
412{
413	(void)printf(" FILEID IFLAG SZ");
414}
415
416int
417ext2fs_print(struct vnode *vp)
418{
419	int flag;
420	struct inode inode, *ip = &inode;
421	struct ext2fs_dinode di;
422	char flagbuf[16], *flags = flagbuf;
423
424	KGETRET(VTOI(vp), &inode, sizeof(struct inode), "vnode's inode");
425	KGETRET(inode.i_e2din, &di, sizeof(struct ext2fs_dinode),
426	    "vnode's dinode");
427
428	inode.i_e2din = &di;
429	flag = ip->i_flag;
430
431#if 0
432	if (flag & IN_LOCKED)
433		*flags++ = 'L';
434	if (flag & IN_WANTED)
435		*flags++ = 'W';
436	if (flag & IN_LWAIT)
437		*flags++ = 'Z';
438#endif
439	if (flag & IN_ACCESS)
440		*flags++ = 'A';
441	if (flag & IN_CHANGE)
442		*flags++ = 'C';
443	if (flag & IN_UPDATE)
444		*flags++ = 'U';
445	if (flag & IN_MODIFIED)
446		*flags++ = 'M';
447	if (flag & IN_RENAME)
448		*flags++ = 'R';
449	if (flag & IN_SHLOCK)
450		*flags++ = 'S';
451	if (flag & IN_EXLOCK)
452		*flags++ = 'E';
453	if (flag == 0)
454		*flags++ = '-';
455	*flags = '\0';
456
457	(void)printf(" %6d %5s %2d", ip->i_number, flagbuf, ip->i_e2fs_size);
458	return (0);
459}
460
461void
462nfs_header(void)
463{
464	(void)printf(" FILEID NFLAG RDEV|SZ");
465}
466
467int
468nfs_print(struct vnode *vp)
469{
470	struct nfsnode nfsnode, *np = &nfsnode;
471	char flagbuf[16], *flags = flagbuf;
472	int flag;
473	char *name;
474	mode_t type;
475
476	KGETRET(VTONFS(vp), &nfsnode, sizeof(nfsnode), "vnode's nfsnode");
477	flag = np->n_flag;
478	if (flag & NFLUSHWANT)
479		*flags++ = 'W';
480	if (flag & NFLUSHINPROG)
481		*flags++ = 'P';
482	if (flag & NMODIFIED)
483		*flags++ = 'M';
484	if (flag & NWRITEERR)
485		*flags++ = 'E';
486	if (flag & NACC)
487		*flags++ = 'A';
488	if (flag & NUPD)
489		*flags++ = 'U';
490	if (flag & NCHG)
491		*flags++ = 'C';
492	if (flag == 0)
493		*flags++ = '-';
494	*flags = '\0';
495
496	(void)printf(" %6ld %5s", np->n_vattr.va_fileid, flagbuf);
497	type = np->n_vattr.va_mode & S_IFMT;
498	if (S_ISCHR(np->n_vattr.va_mode) || S_ISBLK(np->n_vattr.va_mode))
499		if (usenumflag ||
500		    ((name = devname(np->n_vattr.va_rdev, type)) == NULL))
501			(void)printf("   %2d,%-2d", major(np->n_vattr.va_rdev),
502			    minor(np->n_vattr.va_rdev));
503		else
504			(void)printf(" %7s", name);
505	else
506		(void)printf(" %7qd", np->n_size);
507	return (0);
508}
509
510/*
511 * Given a pointer to a mount structure in kernel space,
512 * read it in and return a usable pointer to it.
513 */
514struct mount *
515getmnt(struct mount *maddr)
516{
517	static struct mtab {
518		struct mtab *next;
519		struct mount *maddr;
520		struct mount mount;
521	} *mhead = NULL;
522	struct mtab *mt;
523
524	for (mt = mhead; mt != NULL; mt = mt->next)
525		if (maddr == mt->maddr)
526			return (&mt->mount);
527	if ((mt = malloc(sizeof(struct mtab))) == NULL)
528		err(1, "malloc: mount table");
529	KGETRET(maddr, &mt->mount, sizeof(struct mount), "mount table");
530	mt->maddr = maddr;
531	mt->next = mhead;
532	mhead = mt;
533	return (&mt->mount);
534}
535
536void
537mount_print(struct mount *mp)
538{
539	int flags;
540
541	(void)printf("*** MOUNT ");
542	(void)printf("%.*s %s on %s", MFSNAMELEN,
543	    mp->mnt_stat.f_fstypename, mp->mnt_stat.f_mntfromname,
544	    mp->mnt_stat.f_mntonname);
545	if ((flags = mp->mnt_flag)) {
546		char *comma = "(";
547
548		putchar(' ');
549		/* user visible flags */
550		if (flags & MNT_RDONLY) {
551			(void)printf("%srdonly", comma);
552			flags &= ~MNT_RDONLY;
553			comma = ",";
554		}
555		if (flags & MNT_SYNCHRONOUS) {
556			(void)printf("%ssynchronous", comma);
557			flags &= ~MNT_SYNCHRONOUS;
558			comma = ",";
559		}
560		if (flags & MNT_NOEXEC) {
561			(void)printf("%snoexec", comma);
562			flags &= ~MNT_NOEXEC;
563			comma = ",";
564		}
565		if (flags & MNT_NOSUID) {
566			(void)printf("%snosuid", comma);
567			flags &= ~MNT_NOSUID;
568			comma = ",";
569		}
570		if (flags & MNT_NODEV) {
571			(void)printf("%snodev", comma);
572			flags &= ~MNT_NODEV;
573			comma = ",";
574		}
575		if (flags & MNT_ASYNC) {
576			(void)printf("%sasync", comma);
577			flags &= ~MNT_ASYNC;
578			comma = ",";
579		}
580		if (flags & MNT_EXRDONLY) {
581			(void)printf("%sexrdonly", comma);
582			flags &= ~MNT_EXRDONLY;
583			comma = ",";
584		}
585		if (flags & MNT_EXPORTED) {
586			(void)printf("%sexport", comma);
587			flags &= ~MNT_EXPORTED;
588			comma = ",";
589		}
590		if (flags & MNT_DEFEXPORTED) {
591			(void)printf("%sdefdexported", comma);
592			flags &= ~MNT_DEFEXPORTED;
593			comma = ",";
594		}
595		if (flags & MNT_EXPORTANON) {
596			(void)printf("%sexportanon", comma);
597			flags &= ~MNT_EXPORTANON;
598			comma = ",";
599		}
600		if (flags & MNT_EXKERB) {
601			(void)printf("%sexkerb", comma);
602			flags &= ~MNT_EXKERB;
603			comma = ",";
604		}
605		if (flags & MNT_LOCAL) {
606			(void)printf("%slocal", comma);
607			flags &= ~MNT_LOCAL;
608			comma = ",";
609		}
610		if (flags & MNT_QUOTA) {
611			(void)printf("%squota", comma);
612			flags &= ~MNT_QUOTA;
613			comma = ",";
614		}
615		if (flags & MNT_ROOTFS) {
616			(void)printf("%srootfs", comma);
617			flags &= ~MNT_ROOTFS;
618			comma = ",";
619		}
620		if (flags & MNT_NOATIME) {
621			(void)printf("%snoatime", comma);
622			flags &= ~MNT_NOATIME;
623			comma = ",";
624		}
625		/* filesystem control flags */
626		if (flags & MNT_UPDATE) {
627			(void)printf("%supdate", comma);
628			flags &= ~MNT_UPDATE;
629			comma = ",";
630		}
631		if (flags & MNT_DELEXPORT) {
632			(void)printf("%sdelexport", comma);
633			flags &= ~MNT_DELEXPORT;
634			comma = ",";
635		}
636		if (flags & MNT_RELOAD) {
637			(void)printf("%sreload", comma);
638			flags &= ~MNT_RELOAD;
639			comma = ",";
640		}
641		if (flags & MNT_FORCE) {
642			(void)printf("%sforce", comma);
643			flags &= ~MNT_FORCE;
644			comma = ",";
645		}
646		if (flags & MNT_WANTRDWR) {
647			(void)printf("%swantrdwr", comma);
648			flags &= ~MNT_WANTRDWR;
649			comma = ",";
650		}
651		if (flags & MNT_SOFTDEP) {
652			(void)printf("%ssoftdep", comma);
653			flags &= ~MNT_SOFTDEP;
654			comma = ",";
655		}
656		if (flags)
657			(void)printf("%sunknown_flags:%x", comma, flags);
658		(void)printf(")");
659	}
660	(void)printf("\n");
661}
662
663struct e_vnode *
664loadvnodes(int *avnodes)
665{
666	int mib[2];
667	size_t copysize;
668	struct e_vnode *vnodebase;
669
670	if (memf != NULL) {
671		/*
672		 * do it by hand
673		 */
674		return (kinfo_vnodes(avnodes));
675	}
676	mib[0] = CTL_KERN;
677	mib[1] = KERN_VNODE;
678	if (sysctl(mib, 2, NULL, &copysize, NULL, 0) == -1)
679		err(1, "sysctl: KERN_VNODE");
680	if ((vnodebase = malloc(copysize)) == NULL)
681		err(1, "malloc: vnode table");
682	if (sysctl(mib, 2, vnodebase, &copysize, NULL, 0) == -1)
683		err(1, "sysctl: KERN_VNODE");
684	if (copysize % sizeof(struct e_vnode))
685		errx(1, "vnode size mismatch");
686	*avnodes = copysize / sizeof(struct e_vnode);
687
688	return (vnodebase);
689}
690
691/*
692 * simulate what a running kernel does in in kinfo_vnode
693 */
694struct e_vnode *
695kinfo_vnodes(int *avnodes)
696{
697	struct mntlist mountlist;
698	struct mount *mp, mount;
699	struct vnode *vp, vnode;
700	char *vbuf, *evbuf, *bp;
701	int mib[2], numvnodes;
702	size_t num;
703
704	if (kd == 0) {
705		mib[0] = CTL_KERN;
706		mib[1] = KERN_NUMVNODES;
707		num = sizeof(numvnodes);
708		if (sysctl(mib, 2, &numvnodes, &num, NULL, 0) < 0)
709			err(1, "sysctl(KERN_NUMVNODES) failed");
710	} else
711		KGET(V_NUMV, numvnodes);
712	if ((vbuf = malloc((numvnodes + 20) *
713	    (sizeof(struct vnode *) + sizeof(struct vnode)))) == NULL)
714		err(1, "malloc: vnode buffer");
715	bp = vbuf;
716	evbuf = vbuf + (numvnodes + 20) *
717	    (sizeof(struct vnode *) + sizeof(struct vnode));
718	KGET(V_MOUNTLIST, mountlist);
719	for (num = 0, mp = CIRCLEQ_FIRST(&mountlist); ;
720	    mp = CIRCLEQ_NEXT(&mount, mnt_list)) {
721		KGET2(mp, &mount, sizeof(mount), "mount entry");
722		for (vp = LIST_FIRST(&mount.mnt_vnodelist);
723		    vp != NULL; vp = LIST_NEXT(&vnode, v_mntvnodes)) {
724			KGET2(vp, &vnode, sizeof(vnode), "vnode");
725			if ((bp + sizeof(struct vnode *) +
726			    sizeof(struct vnode)) > evbuf)
727				/* XXX - should realloc */
728				errx(1, "no more room for vnodes");
729			memmove(bp, &vp, sizeof(struct vnode *));
730			bp += sizeof(struct vnode *);
731			memmove(bp, &vnode, sizeof(struct vnode));
732			bp += sizeof(struct vnode);
733			num++;
734		}
735		if (mp == CIRCLEQ_LAST(&mountlist))
736			break;
737	}
738	*avnodes = num;
739	return ((struct e_vnode *)vbuf);
740}
741
742const char hdr[] =
743"   LINE RAW  CAN  OUT  HWT LWT    COL STATE      SESS  PGID DISC\n";
744
745void
746tty2itty(struct tty *tp, struct itty *itp)
747{
748	itp->t_dev = tp->t_dev;
749	itp->t_rawq_c_cc = tp->t_rawq.c_cc;
750	itp->t_canq_c_cc = tp->t_canq.c_cc;
751	itp->t_outq_c_cc = tp->t_outq.c_cc;
752	itp->t_hiwat = tp->t_hiwat;
753	itp->t_lowat = tp->t_lowat;
754	itp->t_column = tp->t_column;
755	itp->t_state = tp->t_state;
756	itp->t_session = tp->t_session;
757	if (tp->t_pgrp != NULL)
758		KGET2(&tp->t_pgrp->pg_id, &itp->t_pgrp_pg_id, sizeof(pid_t), "pgid");
759	itp->t_line = tp->t_line;
760}
761
762void
763ttymode(void)
764{
765	struct ttylist_head tty_head;
766	struct tty *tp, tty;
767	int mib[3], ntty, i;
768	struct itty itty, *itp;
769	size_t nlen;
770
771	if (kd == 0) {
772		mib[0] = CTL_KERN;
773		mib[1] = KERN_TTYCOUNT;
774		nlen = sizeof(ntty);
775		if (sysctl(mib, 2, &ntty, &nlen, NULL, 0) < 0)
776			err(1, "sysctl(KERN_TTYCOUNT) failed");
777	} else
778		KGET(TTY_NTTY, ntty);
779	(void)printf("%d terminal device%s\n", ntty, ntty == 1 ? "" : "s");
780	(void)printf("%s", hdr);
781	if (kd == 0) {
782		mib[0] = CTL_KERN;
783		mib[1] = KERN_TTY;
784		mib[2] = KERN_TTY_INFO;
785		nlen = ntty * sizeof(struct itty);
786		if ((itp = malloc(nlen)) == NULL)
787			err(1, "malloc");
788		if (sysctl(mib, 3, itp, &nlen, NULL, 0) < 0)
789			err(1, "sysctl(KERN_TTY_INFO) failed");
790		for (i = 0; i < ntty; i++)
791			ttyprt(&itp[i]);
792		free(itp);
793	} else {
794		KGET(TTY_TTYLIST, tty_head);
795		for (tp = TAILQ_FIRST(&tty_head); tp;
796		    tp = TAILQ_NEXT(&tty, tty_link)) {
797			KGET2(tp, &tty, sizeof tty, "tty struct");
798			tty2itty(&tty, &itty);
799			ttyprt(&itty);
800		}
801	}
802}
803
804struct {
805	int flag;
806	char val;
807} ttystates[] = {
808	{ TS_WOPEN,	'W'},
809	{ TS_ISOPEN,	'O'},
810	{ TS_CARR_ON,	'C'},
811	{ TS_TIMEOUT,	'T'},
812	{ TS_FLUSH,	'F'},
813	{ TS_BUSY,	'B'},
814	{ TS_ASLEEP,	'A'},
815	{ TS_XCLUDE,	'X'},
816	{ TS_TTSTOP,	'S'},
817	{ TS_TBLOCK,	'K'},
818	{ TS_ASYNC,	'Y'},
819	{ TS_BKSL,	'D'},
820	{ TS_ERASE,	'E'},
821	{ TS_LNCH,	'L'},
822	{ TS_TYPEN,	'P'},
823	{ TS_CNTTB,	'N'},
824	{ 0,		'\0'},
825};
826
827void
828ttyprt(struct itty *tp)
829{
830	char *name, state[20];
831	int i, j;
832
833	if (usenumflag || (name = devname(tp->t_dev, S_IFCHR)) == NULL)
834		(void)printf("%2d,%-3d   ", major(tp->t_dev), minor(tp->t_dev));
835	else
836		(void)printf("%7s ", name);
837	(void)printf("%3d %4d ", tp->t_rawq_c_cc, tp->t_canq_c_cc);
838	(void)printf("%4d %4d %3d %6d ", tp->t_outq_c_cc,
839		tp->t_hiwat, tp->t_lowat, tp->t_column);
840	for (i = j = 0; ttystates[i].flag; i++)
841		if (tp->t_state&ttystates[i].flag)
842			state[j++] = ttystates[i].val;
843	if (j == 0)
844		state[j++] = '-';
845	state[j] = '\0';
846	(void)printf("%-6s %8lx", state, (u_long)tp->t_session & ~KERNBASE);
847	(void)printf("%6d ", tp->t_pgrp_pg_id);
848	switch (tp->t_line) {
849	case TTYDISC:
850		(void)printf("term\n");
851		break;
852	case TABLDISC:
853		(void)printf("tab\n");
854		break;
855	case SLIPDISC:
856		(void)printf("slip\n");
857		break;
858	case PPPDISC:
859		(void)printf("ppp\n");
860		break;
861	case STRIPDISC:
862		(void)printf("strip\n");
863		break;
864	default:
865		(void)printf("%d\n", tp->t_line);
866		break;
867	}
868}
869
870void
871filemode(void)
872{
873	struct file fp, *ffp, *addr;
874	char *buf, flagbuf[16], *fbp;
875	static char *dtypes[] = { "???", "inode", "socket" };
876	int mib[2], maxfile, nfile;
877	size_t len;
878
879	if (kd == 0) {
880		mib[0] = CTL_KERN;
881		mib[1] = KERN_MAXFILES;
882		len = sizeof(maxfile);
883		if (sysctl(mib, 2, &maxfile, &len, NULL, 0) < 0)
884			err(1, "sysctl(KERN_MAXFILES) failed");
885		if (totalflag) {
886			mib[0] = CTL_KERN;
887			mib[1] = KERN_NFILES;
888			len = sizeof(nfile);
889			if (sysctl(mib, 2, &nfile, &len, NULL, 0) < 0)
890				err(1, "sysctl(KERN_NFILES) failed");
891		}
892	} else {
893		KGET(FNL_MAXFILE, maxfile);
894		if (totalflag) {
895			KGET(FNL_NFILE, nfile);
896			(void)printf("%3d/%3d files\n", nfile, maxfile);
897			return;
898		}
899	}
900
901	if (getfiles(&buf, &len) == -1)
902		return;
903	/*
904	 * Getfiles returns in malloc'd memory a pointer to the first file
905	 * structure, and then an array of file structs (whose addresses are
906	 * derivable from the previous entry).
907	 */
908	addr = LIST_FIRST((struct filelist *)buf);
909	ffp = (struct file *)(buf + sizeof(struct filelist));
910	nfile = (len - sizeof(struct filelist)) / sizeof(struct file);
911
912	(void)printf("%d/%d open files\n", nfile, maxfile);
913
914	(void)printf("%*s TYPE       FLG  CNT  MSG  %*s  OFFSET\n",
915	    8, "LOC", 8, "DATA");
916	for (; (char *)ffp < buf + len; addr = LIST_NEXT(ffp, f_list), ffp++) {
917		memmove(&fp, ffp, sizeof fp);
918		if ((unsigned)fp.f_type > DTYPE_SOCKET)
919			continue;
920		(void)printf("%lx ", (long)addr);
921		(void)printf("%-8.8s", dtypes[fp.f_type]);
922		fbp = flagbuf;
923		if (fp.f_flag & FREAD)
924			*fbp++ = 'R';
925		if (fp.f_flag & FWRITE)
926			*fbp++ = 'W';
927		if (fp.f_flag & FAPPEND)
928			*fbp++ = 'A';
929		if (fp.f_flag & FHASLOCK)
930			*fbp++ = 'L';
931		if (fp.f_flag & FASYNC)
932			*fbp++ = 'I';
933		*fbp = '\0';
934		(void)printf("%6s  %3ld", flagbuf, fp.f_count);
935		(void)printf("  %3ld", fp.f_msgcount);
936		(void)printf("  %8.1lx", (long)fp.f_data);
937
938		if (fp.f_offset < 0)
939			(void)printf("  %llx\n", (long long)fp.f_offset);
940		else
941			(void)printf("  %lld\n", (long long)fp.f_offset);
942	}
943	free(buf);
944}
945
946int
947getfiles(char **abuf, size_t *alen)
948{
949	size_t len;
950	int mib[2];
951	char *buf;
952
953	/*
954	 * XXX
955	 * Add emulation of KINFO_FILE here.
956	 */
957	if (memf != NULL)
958		errx(1, "files on dead kernel, not implemented");
959
960	mib[0] = CTL_KERN;
961	mib[1] = KERN_FILE;
962	if (sysctl(mib, 2, NULL, &len, NULL, 0) == -1) {
963		warn("sysctl: KERN_FILE");
964		return (-1);
965	}
966	if ((buf = malloc(len)) == NULL)
967		err(1, "malloc: KERN_FILE");
968	if (sysctl(mib, 2, buf, &len, NULL, 0) == -1) {
969		warn("sysctl: KERN_FILE");
970		free(buf);
971		return (-1);
972	}
973	*abuf = buf;
974	*alen = len;
975	return (0);
976}
977
978/*
979 * swapmode is based on a program called swapinfo written
980 * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
981 */
982void
983swapmode(void)
984{
985	char *header;
986	int hlen = 10, nswap;
987	int div, i, avail, nfree, npfree, used;
988	long blocksize;
989	struct swapent *swdev;
990
991	if (kflag) {
992		header = "1K-blocks";
993		blocksize = 1024;
994		hlen = strlen(header);
995	} else
996		header = getbsize(&hlen, &blocksize);
997
998	nswap = swapctl(SWAP_NSWAP, 0, 0);
999	if (nswap == 0) {
1000		if (!totalflag)
1001			(void)printf("%-11s %*s %8s %8s %8s  %s\n",
1002			    "Device", hlen, header,
1003			    "Used", "Avail", "Capacity", "Priority");
1004		(void)printf("%-11s %*d %8d %8d %5.0f%%\n",
1005		    "Total", hlen, 0, 0, 0, 0.0);
1006		return;
1007	}
1008	if ((swdev = malloc(nswap * sizeof(*swdev))) == NULL)
1009		err(1, "malloc");
1010	if (swapctl(SWAP_STATS, swdev, nswap) == -1)
1011		err(1, "swapctl");
1012
1013	if (!totalflag)
1014		(void)printf("%-11s %*s %8s %8s %8s  %s\n",
1015		    "Device", hlen, header,
1016		    "Used", "Avail", "Capacity", "Priority");
1017
1018	/* Run through swap list, doing the funky monkey. */
1019	div = blocksize / DEV_BSIZE;
1020	avail = nfree = npfree = 0;
1021	for (i = 0; i < nswap; i++) {
1022		int xsize, xfree;
1023
1024		if (!(swdev[i].se_flags & SWF_ENABLE))
1025			continue;
1026
1027		if (!totalflag) {
1028			if (usenumflag)
1029				(void)printf("%2d,%-2d       %*d ",
1030				    major(swdev[i].se_dev),
1031				    minor(swdev[i].se_dev),
1032				    hlen, swdev[i].se_nblks / div);
1033			else
1034				(void)printf("%-11s %*d ", swdev[i].se_path,
1035				    hlen, swdev[i].se_nblks / div);
1036		}
1037
1038		xsize = swdev[i].se_nblks;
1039		used = swdev[i].se_inuse;
1040		xfree = xsize - used;
1041		nfree += (xsize - used);
1042		npfree++;
1043		avail += xsize;
1044		if (totalflag)
1045			continue;
1046		(void)printf("%8d %8d %5.0f%%    %d\n",
1047		    used / div, xfree / div,
1048		    (double)used / (double)xsize * 100.0,
1049		    swdev[i].se_priority);
1050	}
1051	free(swdev);
1052
1053	/*
1054	 * If only one partition has been set up via swapon(8), we don't
1055	 * need to bother with totals.
1056	 */
1057	used = avail - nfree;
1058	if (totalflag) {
1059		(void)printf("%dM/%dM swap space\n",
1060		    used / (1048576 / DEV_BSIZE),
1061		    avail / (1048576 / DEV_BSIZE));
1062		return;
1063	}
1064	if (npfree > 1) {
1065		(void)printf("%-11s %*d %8d %8d %5.0f%%\n",
1066		    "Total", hlen, avail / div, used / div, nfree / div,
1067		    (double)used / (double)avail * 100.0);
1068	}
1069}
1070
1071void
1072usage(void)
1073{
1074	(void)fprintf(stderr,
1075	    "usage: pstat [-fknsTtv] [-M core] [-N system]\n");
1076	exit(1);
1077}
1078