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