pstat.c revision 42955
1/*-
2 * Copyright (c) 1980, 1991, 1993, 1994
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#ifndef lint
35static const char copyright[] =
36"@(#) Copyright (c) 1980, 1991, 1993, 1994\n\
37	The Regents of the University of California.  All rights reserved.\n";
38#endif /* not lint */
39
40#ifndef lint
41#if 0
42static char sccsid[] = "@(#)pstat.c	8.16 (Berkeley) 5/9/95";
43#endif
44static const char rcsid[] =
45	"$Id: pstat.c,v 1.37 1998/08/19 01:32:28 bde Exp $";
46#endif /* not lint */
47
48#include <sys/param.h>
49#include <sys/time.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#include <sys/mount.h>
57#include <sys/uio.h>
58#include <sys/namei.h>
59#include <miscfs/union/union.h>
60#undef KERNEL
61#include <sys/stat.h>
62#include <nfs/rpcv2.h>
63#include <nfs/nfsproto.h>
64#include <nfs/nfs.h>
65#include <nfs/nfsnode.h>
66#include <sys/ioctl.h>
67#include <sys/ioctl_compat.h>	/* XXX NTTYDISC is too well hidden */
68#include <sys/tty.h>
69#include <sys/conf.h>
70#include <sys/rlist.h>
71#include <sys/blist.h>
72
73#include <sys/user.h>
74#include <sys/sysctl.h>
75
76#include <err.h>
77#include <fcntl.h>
78#include <kvm.h>
79#include <limits.h>
80#include <nlist.h>
81#include <stdio.h>
82#include <stdlib.h>
83#include <string.h>
84#include <unistd.h>
85
86struct nlist nl[] = {
87#define VM_SWAPLIST	0
88	{ "_swaplist" },/* list of free swap areas */
89#define NLMANDATORYBEG	1
90#define VM_SWDEVT	1
91	{ "_swdevt" },	/* list of swap devices and sizes */
92#define VM_NSWDEV	2
93	{ "_nswdev" },	/* number of swap devices */
94#define VM_DMMAX	3
95	{ "_dmmax" },	/* maximum size of a swap block */
96#define	V_MOUNTLIST	4
97	{ "_mountlist" },	/* address of head of mount list. */
98#define V_NUMV		5
99	{ "_numvnodes" },
100#define	FNL_NFILE	6
101	{"_nfiles"},
102#define FNL_MAXFILE	7
103	{"_maxfiles"},
104#define NLMANDATORYEND FNL_MAXFILE	/* names up to here are mandatory */
105#define	SCONS		NLMANDATORYEND + 1
106	{ "_cons" },
107#define	SPTY		NLMANDATORYEND + 2
108	{ "_pt_tty" },
109#define	SNPTY		NLMANDATORYEND + 3
110	{ "_npty" },
111#define	VM_SWAPBLIST	NLMANDATORYEND + 4
112	{ "_swapblist" },
113
114#ifdef hp300
115#define	SDCA	(VM_SWAPBLIST+1)
116	{ "_dca_tty" },
117#define	SNDCA	(VM_SWAPBLIST+2)
118	{ "_ndca" },
119#define	SDCM	(VM_SWAPBLIST+3)
120	{ "_dcm_tty" },
121#define	SNDCM	(VM_SWAPBLIST+4)
122	{ "_ndcm" },
123#define	SDCL	(VM_SWAPBLIST+5)
124	{ "_dcl_tty" },
125#define	SNDCL	(VM_SWAPBLIST+6)
126	{ "_ndcl" },
127#define	SITE	(VM_SWAPBLIST+7)
128	{ "_ite_tty" },
129#define	SNITE	(VM_SWAPBLIST+8)
130	{ "_nite" },
131#endif
132
133#ifdef mips
134#define SDC	(VM_SWAPBLIST+1)
135	{ "_dc_tty" },
136#define SNDC	(VM_SWAPBLIST+2)
137	{ "_dc_cnt" },
138#endif
139
140#ifdef __FreeBSD__
141#define SCCONS	(VM_SWAPBLIST+1)
142	{ "_sccons" },
143#define NSCCONS	(VM_SWAPBLIST+2)
144	{ "_nsccons" },
145#define SIO  (VM_SWAPBLIST+3)
146	{ "_sio_tty" },
147#define NSIO (VM_SWAPBLIST+4)
148	{ "_nsio_tty" },
149#define RC  (VM_SWAPBLIST+5)
150	{ "_rc_tty" },
151#define NRC (VM_SWAPBLIST+6)
152	{ "_nrc_tty" },
153#define CY  (VM_SWAPBLIST+7)
154	{ "_cy_tty" },
155#define NCY (VM_SWAPBLIST+8)
156	{ "_ncy_tty" },
157#define SI  (VM_SWAPBLIST+9)
158	{ "_si_tty" },
159#define NSI (VM_SWAPBLIST+10)
160	{ "_si_Nports" },
161#endif
162	{ "" }
163};
164
165int	usenumflag;
166int	totalflag;
167int	swapflag;
168char	*nlistf	= NULL;
169char	*memf	= NULL;
170kvm_t	*kd;
171
172char	*usagestr;
173
174struct {
175	int m_flag;
176	const char *m_name;
177} mnt_flags[] = {
178	{ MNT_RDONLY, "rdonly" },
179	{ MNT_SYNCHRONOUS, "sync" },
180	{ MNT_NOEXEC, "noexec" },
181	{ MNT_NOSUID, "nosuid" },
182	{ MNT_NODEV, "nodev" },
183	{ MNT_UNION, "union" },
184	{ MNT_ASYNC, "async" },
185	{ MNT_NOATIME, "noatime" },
186	{ MNT_EXRDONLY, "exrdonly" },
187	{ MNT_EXPORTED, "exported" },
188	{ MNT_DEFEXPORTED, "defexported" },
189	{ MNT_EXPORTANON, "exportanon" },
190	{ MNT_EXKERB, "exkerb" },
191	{ MNT_LOCAL, "local" },
192	{ MNT_QUOTA, "quota" },
193	{ MNT_ROOTFS, "rootfs" },
194	{ MNT_USER, "user" },
195	{ MNT_UPDATE, "update" },
196	{ MNT_DELEXPORT },
197	{ MNT_UPDATE, "update" },
198	{ MNT_DELEXPORT, "delexport" },
199	{ MNT_RELOAD, "reload" },
200	{ MNT_FORCE, "force" },
201#if 0
202	{ MNT_UNMOUNT, "unmount" },
203	{ MNT_MWAIT, "mwait" },
204	{ MNT_WANTRDWR, "wantrdwr" },
205#endif
206	{ 0 }
207};
208
209
210#define	SVAR(var) __STRING(var)	/* to force expansion */
211#define	KGET(idx, var)							\
212	KGET1(idx, &var, sizeof(var), SVAR(var))
213#define	KGET1(idx, p, s, msg)						\
214	KGET2(nl[idx].n_value, p, s, msg)
215#define	KGET2(addr, p, s, msg)						\
216	if (kvm_read(kd, (u_long)(addr), p, s) != s)			\
217		warnx("cannot read %s: %s", msg, kvm_geterr(kd))
218#define	KGETN(idx, var)							\
219	KGET1N(idx, &var, sizeof(var), SVAR(var))
220#define	KGET1N(idx, p, s, msg)						\
221	KGET2N(nl[idx].n_value, p, s, msg)
222#define	KGET2N(addr, p, s, msg)						\
223	((kvm_read(kd, (u_long)(addr), p, s) == s) ? 1 : 0)
224#define	KGETRET(addr, p, s, msg)					\
225	if (kvm_read(kd, (u_long)(addr), p, s) != s) {			\
226		warnx("cannot read %s: %s", msg, kvm_geterr(kd));	\
227		return (0);						\
228	}
229
230void	filemode __P((void));
231int	getfiles __P((char **, int *));
232struct mount *
233	getmnt __P((struct mount *));
234struct e_vnode *
235	kinfo_vnodes __P((int *));
236struct e_vnode *
237	loadvnodes __P((int *));
238void	mount_print __P((struct mount *));
239void	nfs_header __P((void));
240int	nfs_print __P((struct vnode *));
241void	swapmode __P((void));
242void	ttymode __P((void));
243void	ttyprt __P((struct tty *, int));
244void	ttytype __P((struct tty *, char *, int, int, int));
245void	ufs_header __P((void));
246int	ufs_print __P((struct vnode *));
247void	union_header __P((void));
248int	union_print __P((struct vnode *));
249static void usage __P((void));
250void	vnode_header __P((void));
251void	vnode_print __P((struct vnode *, struct vnode *));
252void	vnodemode __P((void));
253
254int
255main(argc, argv)
256	int argc;
257	char *argv[];
258{
259	int ch, i, quit, ret;
260	int fileflag, ttyflag, vnodeflag;
261	char buf[_POSIX2_LINE_MAX],*opts;
262
263	fileflag = swapflag = ttyflag = vnodeflag = 0;
264
265	/* We will behave like good old swapinfo if thus invoked */
266	opts = strrchr(argv[0],'/');
267	if (opts)
268		opts++;
269	else
270		opts = argv[0];
271	if (!strcmp(opts,"swapinfo")) {
272		swapflag = 1;
273		opts = "kM:N:";
274		usagestr = "swapinfo [-k] [-M core] [-N system]";
275	} else {
276		opts = "TM:N:fiknstv";
277		usagestr = "pstat [-Tfknstv] [-M core] [-N system]";
278	}
279
280	while ((ch = getopt(argc, argv, opts)) != -1)
281		switch (ch) {
282		case 'f':
283			fileflag = 1;
284			break;
285		case 'k':
286			putenv("BLOCKSIZE=1K");
287			break;
288		case 'M':
289			memf = optarg;
290			break;
291		case 'N':
292			nlistf = optarg;
293			break;
294		case 'n':
295			usenumflag = 1;
296			break;
297		case 's':
298			++swapflag;
299			break;
300		case 'T':
301			totalflag = 1;
302			break;
303		case 't':
304			ttyflag = 1;
305			break;
306		case 'v':
307		case 'i':		/* Backward compatibility. */
308			fprintf(stderr, "vnode mode not supported\n");
309			exit(1);
310#if 0
311			vnodeflag = 1;
312			break;
313#endif
314		default:
315			usage();
316		}
317	argc -= optind;
318	argv += optind;
319
320	/*
321	 * Discard setgid privileges if not the running kernel so that bad
322	 * guys can't print interesting stuff from kernel memory.
323	 */
324	if (nlistf != NULL || memf != NULL)
325		(void)setgid(getgid());
326
327	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, buf)) == 0)
328		errx(1, "kvm_openfiles: %s", buf);
329	if ((ret = kvm_nlist(kd, nl)) != 0) {
330		if (ret == -1)
331			errx(1, "kvm_nlist: %s", kvm_geterr(kd));
332		for (i = NLMANDATORYBEG, quit = 0; i <= NLMANDATORYEND; i++)
333			if (!nl[i].n_value) {
334				quit = 1;
335				warnx("undefined symbol: %s", nl[i].n_name);
336			}
337		if (quit)
338			exit(1);
339	}
340	if (!(fileflag | vnodeflag | ttyflag | swapflag | totalflag))
341		usage();
342	if (fileflag || totalflag)
343		filemode();
344	if (vnodeflag)
345		vnodemode();
346	if (ttyflag)
347		ttymode();
348	if (swapflag || totalflag)
349		swapmode();
350	exit (0);
351}
352
353static void
354usage()
355{
356	fprintf(stderr, "usage: %s\n", usagestr);
357	exit (1);
358}
359
360struct e_vnode {
361	struct vnode *avnode;
362	struct vnode vnode;
363};
364
365void
366vnodemode()
367{
368	struct e_vnode *e_vnodebase, *endvnode, *evp;
369	struct vnode *vp;
370	struct mount *maddr, *mp;
371	int numvnodes;
372
373	e_vnodebase = loadvnodes(&numvnodes);
374	if (totalflag) {
375		(void)printf("%7d vnodes\n", numvnodes);
376		return;
377	}
378	endvnode = e_vnodebase + numvnodes;
379	(void)printf("%d active vnodes\n", numvnodes);
380
381
382#define ST	mp->mnt_stat
383	maddr = NULL;
384	for (evp = e_vnodebase; evp < endvnode; evp++) {
385		vp = &evp->vnode;
386		if (vp->v_mount != maddr) {
387			/*
388			 * New filesystem
389			 */
390			if ((mp = getmnt(vp->v_mount)) == NULL)
391				continue;
392			maddr = vp->v_mount;
393			mount_print(mp);
394			vnode_header();
395			if (!strcmp(ST.f_fstypename, "ufs") ||
396			    !strcmp(ST.f_fstypename, "mfs"))
397				ufs_header();
398			else if (!strcmp(ST.f_fstypename, "nfs"))
399				nfs_header();
400			else if (!strcmp(ST.f_fstypename, "union"))
401				union_header();
402			(void)printf("\n");
403		}
404		vnode_print(evp->avnode, vp);
405		if (!strcmp(ST.f_fstypename, "ufs") ||
406		    !strcmp(ST.f_fstypename, "mfs"))
407			ufs_print(vp);
408		else if (!strcmp(ST.f_fstypename, "nfs"))
409			nfs_print(vp);
410		else if (!strcmp(ST.f_fstypename, "union"))
411			union_print(vp);
412		(void)printf("\n");
413	}
414	free(e_vnodebase);
415}
416
417void
418vnode_header()
419{
420	(void)printf("ADDR     TYP VFLAG  USE HOLD");
421}
422
423void
424vnode_print(avnode, vp)
425	struct vnode *avnode;
426	struct vnode *vp;
427{
428	char *type, flags[16];
429	char *fp = flags;
430	int flag;
431
432	/*
433	 * set type
434	 */
435	switch (vp->v_type) {
436	case VNON:
437		type = "non"; break;
438	case VREG:
439		type = "reg"; break;
440	case VDIR:
441		type = "dir"; break;
442	case VBLK:
443		type = "blk"; break;
444	case VCHR:
445		type = "chr"; break;
446	case VLNK:
447		type = "lnk"; break;
448	case VSOCK:
449		type = "soc"; break;
450	case VFIFO:
451		type = "fif"; break;
452	case VBAD:
453		type = "bad"; break;
454	default:
455		type = "unk"; break;
456	}
457	/*
458	 * gather flags
459	 */
460	flag = vp->v_flag;
461	if (flag & VROOT)
462		*fp++ = 'R';
463	if (flag & VTEXT)
464		*fp++ = 'T';
465	if (flag & VSYSTEM)
466		*fp++ = 'S';
467	if (flag & VISTTY)
468		*fp++ = 't';
469	if (flag & VXLOCK)
470		*fp++ = 'L';
471	if (flag & VXWANT)
472		*fp++ = 'W';
473	if (flag & VBWAIT)
474		*fp++ = 'B';
475	if (flag & VALIASED)
476		*fp++ = 'A';
477	if (flag & VOBJBUF)
478		*fp++ = 'V';
479	if (flag & VAGE)
480		*fp++ = 'a';
481	if (flag & VOLOCK)
482		*fp++ = 'l';
483	if (flag & VOWANT)
484		*fp++ = 'w';
485	if (flag == 0)
486		*fp++ = '-';
487	*fp = '\0';
488	(void)printf("%8lx %s %5s %4d %4d",
489	    (u_long)(void *)avnode, type, flags, vp->v_usecount, vp->v_holdcnt);
490}
491
492void
493ufs_header()
494{
495	(void)printf(" FILEID IFLAG RDEV|SZ");
496}
497
498int
499ufs_print(vp)
500	struct vnode *vp;
501{
502	int flag;
503	struct inode inode, *ip = &inode;
504	char flagbuf[16], *flags = flagbuf;
505	char *name;
506	mode_t type;
507
508	KGETRET(VTOI(vp), &inode, sizeof(struct inode), "vnode's inode");
509	flag = ip->i_flag;
510	if (flag & IN_RENAME)
511		*flags++ = 'R';
512	if (flag & IN_UPDATE)
513		*flags++ = 'U';
514	if (flag & IN_ACCESS)
515		*flags++ = 'A';
516	if (flag & IN_CHANGE)
517		*flags++ = 'C';
518	if (flag & IN_MODIFIED)
519		*flags++ = 'M';
520	if (flag & IN_SHLOCK)
521		*flags++ = 'S';
522	if (flag & IN_EXLOCK)
523		*flags++ = 'E';
524	if (flag == 0)
525		*flags++ = '-';
526	*flags = '\0';
527
528	(void)printf(" %6d %5s", ip->i_number, flagbuf);
529	type = ip->i_mode & S_IFMT;
530	if (S_ISCHR(ip->i_mode) || S_ISBLK(ip->i_mode))
531		if (usenumflag || ((name = devname(ip->i_rdev, type)) == NULL))
532			(void)printf("   %2d,%-2d",
533			    major(ip->i_rdev), minor(ip->i_rdev));
534		else
535			(void)printf(" %7s", name);
536	else
537		(void)printf(" %7qd", ip->i_size);
538	return (0);
539}
540
541void
542nfs_header()
543{
544	(void)printf(" FILEID NFLAG RDEV|SZ");
545}
546
547int
548nfs_print(vp)
549	struct vnode *vp;
550{
551	struct nfsnode nfsnode, *np = &nfsnode;
552	char flagbuf[16], *flags = flagbuf;
553	int flag;
554	char *name;
555	mode_t type;
556
557	KGETRET(VTONFS(vp), &nfsnode, sizeof(nfsnode), "vnode's nfsnode");
558	flag = np->n_flag;
559	if (flag & NFLUSHWANT)
560		*flags++ = 'W';
561	if (flag & NFLUSHINPROG)
562		*flags++ = 'P';
563	if (flag & NMODIFIED)
564		*flags++ = 'M';
565	if (flag & NWRITEERR)
566		*flags++ = 'E';
567	if (flag & NQNFSNONCACHE)
568		*flags++ = 'X';
569	if (flag & NQNFSWRITE)
570		*flags++ = 'O';
571	if (flag & NQNFSEVICTED)
572		*flags++ = 'G';
573	if (flag == 0)
574		*flags++ = '-';
575	*flags = '\0';
576
577#define VT	np->n_vattr
578	(void)printf(" %6ld %5s", VT.va_fileid, flagbuf);
579	type = VT.va_mode & S_IFMT;
580	if (S_ISCHR(VT.va_mode) || S_ISBLK(VT.va_mode))
581		if (usenumflag || ((name = devname(VT.va_rdev, type)) == NULL))
582			(void)printf("   %2d,%-2d",
583			    major(VT.va_rdev), minor(VT.va_rdev));
584		else
585			(void)printf(" %7s", name);
586	else
587		(void)printf(" %7qd", np->n_size);
588	return (0);
589}
590
591void
592union_header()
593{
594	(void)printf("    UPPER    LOWER");
595}
596
597int
598union_print(vp)
599	struct vnode *vp;
600{
601	struct union_node unode, *up = &unode;
602
603	KGETRET(VTOUNION(vp), &unode, sizeof(unode), "vnode's unode");
604
605	(void)printf(" %8lx %8lx", (u_long)(void *)up->un_uppervp,
606	    (u_long)(void *)up->un_lowervp);
607	return (0);
608}
609
610/*
611 * Given a pointer to a mount structure in kernel space,
612 * read it in and return a usable pointer to it.
613 */
614struct mount *
615getmnt(maddr)
616	struct mount *maddr;
617{
618	static struct mtab {
619		struct mtab *next;
620		struct mount *maddr;
621		struct mount mount;
622	} *mhead = NULL;
623	struct mtab *mt;
624
625	for (mt = mhead; mt != NULL; mt = mt->next)
626		if (maddr == mt->maddr)
627			return (&mt->mount);
628	if ((mt = malloc(sizeof(struct mtab))) == NULL)
629		errx(1, "malloc");
630	KGETRET(maddr, &mt->mount, sizeof(struct mount), "mount table");
631	mt->maddr = maddr;
632	mt->next = mhead;
633	mhead = mt;
634	return (&mt->mount);
635}
636
637void
638mount_print(mp)
639	struct mount *mp;
640{
641	int flags;
642	const char *type;
643
644#define ST	mp->mnt_stat
645	(void)printf("*** MOUNT %s %s on %s", ST.f_fstypename,
646	    ST.f_mntfromname, ST.f_mntonname);
647	if ((flags = mp->mnt_flag)) {
648		int i;
649		const char *sep = " (";
650
651		for (i = 0; mnt_flags[i].m_flag; i++) {
652			if (flags & mnt_flags[i].m_flag) {
653				(void)printf("%s%s", sep, mnt_flags[i].m_name);
654				flags &= ~mnt_flags[i].m_flag;
655				sep = ",";
656			}
657		}
658		if (flags)
659			(void)printf("%sunknown_flags:%x", sep, flags);
660		(void)printf(")");
661	}
662	(void)printf("\n");
663#undef ST
664}
665
666struct e_vnode *
667loadvnodes(avnodes)
668	int *avnodes;
669{
670	int mib[2];
671	size_t copysize;
672	struct e_vnode *vnodebase;
673
674	if (memf != NULL) {
675		/*
676		 * do it by hand
677		 */
678		return (kinfo_vnodes(avnodes));
679	}
680	mib[0] = CTL_KERN;
681	mib[1] = KERN_VNODE;
682	if (sysctl(mib, 2, NULL, &copysize, NULL, 0) == -1)
683		err(1, "sysctl: KERN_VNODE");
684	if ((vnodebase = malloc(copysize)) == NULL)
685		errx(1, "malloc");
686	if (sysctl(mib, 2, vnodebase, &copysize, NULL, 0) == -1)
687		err(1, "sysctl: KERN_VNODE");
688	if (copysize % sizeof(struct e_vnode))
689		errx(1, "vnode size mismatch");
690	*avnodes = copysize / sizeof(struct e_vnode);
691
692	return (vnodebase);
693}
694
695/*
696 * simulate what a running kernel does in in kinfo_vnode
697 */
698struct e_vnode *
699kinfo_vnodes(avnodes)
700	int *avnodes;
701{
702	struct mntlist mountlist;
703	struct mount *mp, mount, *mp_next;
704	struct vnode *vp, vnode, *vp_next;
705	char *vbuf, *evbuf, *bp;
706	int num, numvnodes;
707
708#define VPTRSZ  sizeof(struct vnode *)
709#define VNODESZ sizeof(struct vnode)
710
711	KGET(V_NUMV, numvnodes);
712	if ((vbuf = malloc((numvnodes + 20) * (VPTRSZ + VNODESZ))) == NULL)
713		errx(1, "malloc");
714	bp = vbuf;
715	evbuf = vbuf + (numvnodes + 20) * (VPTRSZ + VNODESZ);
716	KGET(V_MOUNTLIST, mountlist);
717	for (num = 0, mp = mountlist.cqh_first; ; mp = mp_next) {
718		KGET2(mp, &mount, sizeof(mount), "mount entry");
719		mp_next = mount.mnt_list.cqe_next;
720		for (vp = mount.mnt_vnodelist.lh_first;
721		    vp != NULL; vp = vp_next) {
722			KGET2(vp, &vnode, sizeof(vnode), "vnode");
723			vp_next = vnode.v_mntvnodes.le_next;
724			if ((bp + VPTRSZ + VNODESZ) > evbuf)
725				/* XXX - should realloc */
726				errx(1, "no more room for vnodes");
727			memmove(bp, &vp, VPTRSZ);
728			bp += VPTRSZ;
729			memmove(bp, &vnode, VNODESZ);
730			bp += VNODESZ;
731			num++;
732		}
733		if (mp == mountlist.cqh_last)
734			break;
735	}
736	*avnodes = num;
737	return ((struct e_vnode *)vbuf);
738}
739
740char hdr[] =
741"  LINE RAW CAN OUT IHIWT ILOWT OHWT LWT     COL STATE  SESS      PGID DISC\n";
742int ttyspace = 128;
743
744void
745ttymode()
746{
747	struct tty *tty;
748
749	if ((tty = malloc(ttyspace * sizeof(*tty))) == NULL)
750		errx(1, "malloc");
751#if !defined(hp300) && !defined(mips)
752	if (nl[SCONS].n_type != 0) {
753		(void)printf("1 console\n");
754		KGET(SCONS, *tty);
755		(void)printf(hdr);
756		ttyprt(&tty[0], 0);
757	}
758#endif
759#ifdef vax
760	if (nl[SNQD].n_type != 0)
761		qdss();
762	if (nl[SNDZ].n_type != 0)
763		ttytype(tty, "dz", SDZ, SNDZ, 0);
764	if (nl[SNDH].n_type != 0)
765		ttytype(tty, "dh", SDH, SNDH, 0);
766	if (nl[SNDMF].n_type != 0)
767		ttytype(tty, "dmf", SDMF, SNDMF, 0);
768	if (nl[SNDHU].n_type != 0)
769		ttytype(tty, "dhu", SDHU, SNDHU, 0);
770	if (nl[SNDMZ].n_type != 0)
771		ttytype(tty, "dmz", SDMZ, SNDMZ, 0);
772#endif
773#ifdef tahoe
774	if (nl[SNVX].n_type != 0)
775		ttytype(tty, "vx", SVX, SNVX, 0);
776	if (nl[SNMP].n_type != 0)
777		ttytype(tty, "mp", SMP, SNMP, 0);
778#endif
779#ifdef hp300
780	if (nl[SNITE].n_type != 0)
781		ttytype(tty, "ite", SITE, SNITE, 0);
782	if (nl[SNDCA].n_type != 0)
783		ttytype(tty, "dca", SDCA, SNDCA, 0);
784	if (nl[SNDCM].n_type != 0)
785		ttytype(tty, "dcm", SDCM, SNDCM, 0);
786	if (nl[SNDCL].n_type != 0)
787		ttytype(tty, "dcl", SDCL, SNDCL, 0);
788#endif
789#ifdef mips
790	if (nl[SNDC].n_type != 0)
791		ttytype(tty, "dc", SDC, SNDC, 0);
792#endif
793#ifdef __FreeBSD__
794	if (nl[NSCCONS].n_type != 0)
795		ttytype(tty, "vty", SCCONS, NSCCONS, 0);
796	if (nl[NSIO].n_type != 0)
797		ttytype(tty, "sio", SIO, NSIO, 0);
798	if (nl[NRC].n_type != 0)
799		ttytype(tty, "rc", RC, NRC, 0);
800	if (nl[NCY].n_type != 0)
801		ttytype(tty, "cy", CY, NCY, 0);
802	if (nl[NSI].n_type != 0)
803		ttytype(tty, "si", SI, NSI, 1);
804#endif
805	if (nl[SNPTY].n_type != 0)
806		ttytype(tty, "pty", SPTY, SNPTY, 0);
807}
808
809void
810ttytype(tty, name, type, number, indir)
811	struct tty *tty;
812	char *name;
813	int type, number, indir;
814{
815	struct tty *tp;
816	int ntty;
817	struct tty **ttyaddr;
818
819	if (tty == NULL)
820		return;
821	KGET(number, ntty);
822	(void)printf("%d %s %s\n", ntty, name, (ntty == 1) ? "line" : "lines");
823	if (ntty > ttyspace) {
824		ttyspace = ntty;
825		if ((tty = realloc(tty, ttyspace * sizeof(*tty))) == 0)
826			errx(1, "realloc");
827	}
828	if (indir) {
829		KGET(type, ttyaddr);
830		KGET2(ttyaddr, tty, ntty * sizeof(struct tty), "tty structs");
831	} else {
832		KGET1(type, tty, ntty * sizeof(struct tty), "tty structs");
833	}
834	(void)printf(hdr);
835	for (tp = tty; tp < &tty[ntty]; tp++)
836		ttyprt(tp, tp - tty);
837}
838
839struct {
840	int flag;
841	char val;
842} ttystates[] = {
843#ifdef TS_WOPEN
844	{ TS_WOPEN,	'W'},
845#endif
846	{ TS_ISOPEN,	'O'},
847	{ TS_CARR_ON,	'C'},
848#ifdef TS_CONNECTED
849	{ TS_CONNECTED,	'c'},
850#endif
851	{ TS_TIMEOUT,	'T'},
852	{ TS_FLUSH,	'F'},
853	{ TS_BUSY,	'B'},
854#ifdef TS_ASLEEP
855	{ TS_ASLEEP,	'A'},
856#endif
857#ifdef TS_SO_OLOWAT
858	{ TS_SO_OLOWAT,	'A'},
859#endif
860#ifdef TS_SO_OCOMPLETE
861	{ TS_SO_OCOMPLETE, 'a'},
862#endif
863	{ TS_XCLUDE,	'X'},
864	{ TS_TTSTOP,	'S'},
865#ifdef TS_CAR_OFLOW
866	{ TS_CAR_OFLOW,	'm'},
867#endif
868#ifdef TS_CTS_OFLOW
869	{ TS_CTS_OFLOW,	'o'},
870#endif
871#ifdef TS_DSR_OFLOW
872	{ TS_DSR_OFLOW,	'd'},
873#endif
874	{ TS_TBLOCK,	'K'},
875	{ TS_ASYNC,	'Y'},
876	{ TS_BKSL,	'D'},
877	{ TS_ERASE,	'E'},
878	{ TS_LNCH,	'L'},
879	{ TS_TYPEN,	'P'},
880	{ TS_CNTTB,	'N'},
881#ifdef TS_CAN_BYPASS_L_RINT
882	{ TS_CAN_BYPASS_L_RINT, 'l'},
883#endif
884#ifdef TS_SNOOP
885	{ TS_SNOOP,     's'},
886#endif
887#ifdef TS_ZOMBIE
888	{ TS_ZOMBIE,	'Z'},
889#endif
890	{ 0,	       '\0'},
891};
892
893void
894ttyprt(tp, line)
895	struct tty *tp;
896	int line;
897{
898	int i, j;
899	pid_t pgid;
900	char *name, state[20];
901
902	if (usenumflag || tp->t_dev == 0 ||
903	   (name = devname(tp->t_dev, S_IFCHR)) == NULL)
904		(void)printf("%7d ", line);
905	else
906		(void)printf("%7s ", name);
907	(void)printf("%2d %3d ", tp->t_rawq.c_cc, tp->t_canq.c_cc);
908	(void)printf("%3d %5d %5d %4d %3d %7d ", tp->t_outq.c_cc,
909		tp->t_ihiwat, tp->t_ilowat, tp->t_ohiwat, tp->t_olowat,
910		tp->t_column);
911	for (i = j = 0; ttystates[i].flag; i++)
912		if (tp->t_state&ttystates[i].flag)
913			state[j++] = ttystates[i].val;
914	if (j == 0)
915		state[j++] = '-';
916	state[j] = '\0';
917	(void)printf("%-6s %8lx", state, (u_long)(void *)tp->t_session);
918	pgid = 0;
919	if (tp->t_pgrp != NULL)
920		KGET2(&tp->t_pgrp->pg_id, &pgid, sizeof(pid_t), "pgid");
921	(void)printf("%6d ", pgid);
922	switch (tp->t_line) {
923	case TTYDISC:
924		(void)printf("term\n");
925		break;
926	case NTTYDISC:
927		(void)printf("ntty\n");
928		break;
929	case TABLDISC:
930		(void)printf("tab\n");
931		break;
932	case SLIPDISC:
933		(void)printf("slip\n");
934		break;
935	case PPPDISC:
936		(void)printf("ppp\n");
937		break;
938	default:
939		(void)printf("%d\n", tp->t_line);
940		break;
941	}
942}
943
944void
945filemode()
946{
947	struct file *fp;
948	struct file *addr;
949	char *buf, flagbuf[16], *fbp;
950	int len, maxfile, nfile;
951	static char *dtypes[] = { "???", "inode", "socket" };
952
953	KGET(FNL_MAXFILE, maxfile);
954	if (totalflag) {
955		KGET(FNL_NFILE, nfile);
956		(void)printf("%3d/%3d files\n", nfile, maxfile);
957		return;
958	}
959	if (getfiles(&buf, &len) == -1)
960		return;
961	/*
962	 * Getfiles returns in malloc'd memory a pointer to the first file
963	 * structure, and then an array of file structs (whose addresses are
964	 * derivable from the previous entry).
965	 */
966	addr = ((struct filelist *)buf)->lh_first;
967	fp = (struct file *)(buf + sizeof(struct filelist));
968	nfile = (len - sizeof(struct filelist)) / sizeof(struct file);
969
970	(void)printf("%d/%d open files\n", nfile, maxfile);
971	(void)printf("   LOC   TYPE    FLG     CNT  MSG    DATA    OFFSET\n");
972	for (; (char *)fp < buf + len; addr = fp->f_list.le_next, fp++) {
973		if ((unsigned)fp->f_type > DTYPE_SOCKET)
974			continue;
975		(void)printf("%8lx ", (u_long)(void *)addr);
976		(void)printf("%-8.8s", dtypes[fp->f_type]);
977		fbp = flagbuf;
978		if (fp->f_flag & FREAD)
979			*fbp++ = 'R';
980		if (fp->f_flag & FWRITE)
981			*fbp++ = 'W';
982		if (fp->f_flag & FAPPEND)
983			*fbp++ = 'A';
984#ifdef FSHLOCK	/* currently gone */
985		if (fp->f_flag & FSHLOCK)
986			*fbp++ = 'S';
987		if (fp->f_flag & FEXLOCK)
988			*fbp++ = 'X';
989#endif
990		if (fp->f_flag & FASYNC)
991			*fbp++ = 'I';
992		*fbp = '\0';
993		(void)printf("%6s  %3d", flagbuf, fp->f_count);
994		(void)printf("  %3d", fp->f_msgcount);
995		(void)printf("  %8lx", (u_long)(void *)fp->f_data);
996		if (fp->f_offset < 0)
997			(void)printf("  %qx\n", fp->f_offset);
998		else
999			(void)printf("  %qd\n", fp->f_offset);
1000	}
1001	free(buf);
1002}
1003
1004int
1005getfiles(abuf, alen)
1006	char **abuf;
1007	int *alen;
1008{
1009	size_t len;
1010	int mib[2];
1011	char *buf;
1012
1013	/*
1014	 * XXX
1015	 * Add emulation of KINFO_FILE here.
1016	 */
1017	if (memf != NULL)
1018		errx(1, "files on dead kernel, not implemented");
1019
1020	mib[0] = CTL_KERN;
1021	mib[1] = KERN_FILE;
1022	if (sysctl(mib, 2, NULL, &len, NULL, 0) == -1) {
1023		warn("sysctl: KERN_FILE");
1024		return (-1);
1025	}
1026	if ((buf = malloc(len)) == NULL)
1027		errx(1, "malloc");
1028	if (sysctl(mib, 2, buf, &len, NULL, 0) == -1) {
1029		warn("sysctl: KERN_FILE");
1030		return (-1);
1031	}
1032	*abuf = buf;
1033	*alen = len;
1034	return (0);
1035}
1036
1037/*
1038 * scanradix() - used by swapmode() to scan the swap device's new style
1039 * 		 radix tree
1040 */
1041
1042#define TABME	tab, tab, ""
1043
1044int
1045scanradix(
1046	blmeta_t *scan,
1047	daddr_t blk,
1048	daddr_t radix,
1049	daddr_t skip,
1050	daddr_t count,
1051	int dmmax,
1052	int nswdev,
1053	long *perdev,
1054	int tab
1055) {
1056	blmeta_t meta;
1057
1058	KGET2(scan, &meta, sizeof(meta), "blmeta_t");
1059
1060	/*
1061	 * Terminator
1062	 */
1063	if (meta.bm_bighint == (daddr_t)-1) {
1064		if (swapflag > 1) {
1065			printf("%*.*s(0x%06x,%d) Terminator\n",
1066			    TABME,
1067			    blk,
1068			    radix
1069			);
1070		}
1071		return(-1);
1072	}
1073
1074	if (radix == BLIST_BMAP_RADIX) {
1075		/*
1076		 * Leaf bitmap
1077		 */
1078		int i;
1079
1080		if (swapflag > 1) {
1081			printf("%*.*s(0x%06x,%d) Bitmap %08x big=%d\n",
1082			    TABME,
1083			    blk,
1084			    radix,
1085			    (int)meta.u.bmu_bitmap,
1086			    meta.bm_bighint
1087			);
1088		}
1089
1090		/*
1091		 * If not all allocated, count.
1092		 */
1093		if (meta.u.bmu_bitmap != 0) {
1094			for (i = 0; i < BLIST_BMAP_RADIX && i < count; ++i) {
1095				/*
1096				 * A 0 bit means allocated
1097				 */
1098				if ((meta.u.bmu_bitmap & (1 << i))) {
1099					int t = 0;
1100
1101					if (nswdev)
1102						t = (blk + i) / dmmax % nswdev;
1103					++perdev[t];
1104				}
1105			}
1106		}
1107	} else if (meta.u.bmu_avail == radix) {
1108		/*
1109		 * Meta node if all free
1110		 */
1111		if (swapflag > 1) {
1112			printf("%*.*s(0x%06x,%d) Submap ALL-FREE {\n",
1113			    TABME,
1114			    blk,
1115			    radix,
1116			    (int)meta.u.bmu_avail,
1117			    meta.bm_bighint
1118			);
1119		}
1120		/*
1121		 * Note: both dmmax and radix are powers of 2.  However, dmmax
1122		 * may be larger then radix so use a smaller increment if
1123		 * necessary.
1124		 */
1125		{
1126			int t;
1127			int tinc = dmmax;
1128
1129			while (tinc > radix)
1130				tinc >>= 1;
1131
1132			for (t = blk; t < blk + radix; t += tinc) {
1133				if (nswdev)
1134					perdev[0] += tinc;
1135				else
1136					perdev[t / dmmax % nswdev] += tinc;
1137			}
1138		}
1139	} else if (meta.u.bmu_avail == 0) {
1140		/*
1141		 * Meta node if all used
1142		 */
1143		if (swapflag > 1) {
1144			printf("%*.*s(0x%06x,%d) Submap ALL-ALLOCATED\n",
1145			    TABME,
1146			    blk,
1147			    radix,
1148			    (int)meta.u.bmu_avail,
1149			    meta.bm_bighint
1150			);
1151		}
1152	} else {
1153		/*
1154		 * Meta node if not all free
1155		 */
1156		int i;
1157		int next_skip;
1158
1159		radix >>= BLIST_META_RADIX_SHIFT;
1160		next_skip = skip >> BLIST_META_RADIX_SHIFT;
1161
1162		if (swapflag > 1) {
1163			printf("%*.*s(0x%06x,%d) Submap avail=%d big=%d {\n",
1164			    TABME,
1165			    blk,
1166			    radix,
1167			    (int)meta.u.bmu_avail,
1168			    meta.bm_bighint
1169			);
1170		}
1171
1172		for (i = 1; i <= skip; i += next_skip) {
1173			int r;
1174			daddr_t vcount = (count > radix) ? radix : count;
1175
1176			r = scanradix(
1177			    &scan[i],
1178			    blk,
1179			    radix,
1180			    next_skip - 1,
1181			    vcount,
1182			    dmmax,
1183			    nswdev,
1184			    perdev,
1185			    tab + 4
1186			);
1187			if (r < 0)
1188				break;
1189			blk += radix;
1190		}
1191		if (swapflag > 1) {
1192			printf("%*.*s}\n", TABME);
1193		}
1194	}
1195	return(0);
1196}
1197
1198
1199/*
1200 * swapmode is based on a program called swapinfo written
1201 * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
1202 */
1203void
1204swapmode(void)
1205{
1206	char *header, *p;
1207	int hlen, nswdev, dmmax;
1208	int i, div, mul, avail, nfree, npfree, used;
1209	struct swdevt *sw;
1210	long blocksize, *perdev;
1211	struct rlist head;
1212	struct rlisthdr swaplist;
1213	struct blist	*swapblist = NULL;
1214	u_long ptr;
1215
1216	KGET(VM_NSWDEV, nswdev);
1217	KGET(VM_DMMAX, dmmax);	/* PAGE_BSIZE'd or PAGE_SIZE'd depending */
1218	if (!KGET1N(VM_SWAPLIST, &swaplist, sizeof swaplist, "swaplist")) {
1219	    KGET1(VM_SWAPBLIST, &swapblist, sizeof swapblist, "swapblist");
1220	}
1221
1222	if ((sw = malloc(nswdev * sizeof(*sw))) == NULL ||
1223	    (perdev = malloc(nswdev * sizeof(*perdev))) == NULL)
1224		errx(1, "malloc");
1225	KGET1(VM_SWDEVT, &ptr, sizeof ptr, "swdevt");
1226	KGET2(ptr, sw, nswdev * sizeof(*sw), "*swdevt");
1227
1228	/* Count up swap space. */
1229	nfree = 0;
1230	memset(perdev, 0, nswdev * sizeof(*perdev));
1231
1232	if (swapblist) {
1233		/*
1234		 * New swap radix tree (ugh!)
1235		 */
1236		struct blist blcopy = { 0 };
1237		KGET2(swapblist, &blcopy, sizeof(blcopy), "*swapblist");
1238		if (swapflag > 1) {
1239			printf("radix tree: %d/%d/%d blocks, %dK wired\n",
1240				blcopy.bl_free,
1241				blcopy.bl_blocks,
1242				blcopy.bl_radix,
1243				(blcopy.bl_rootblks * sizeof(blmeta_t) + 1023)/
1244				    1024
1245			);
1246		}
1247		scanradix(blcopy.bl_root, 0, blcopy.bl_radix, blcopy.bl_skip, blcopy.bl_rootblks, dmmax, nswdev, perdev, 0);
1248	} else {
1249		/*
1250		 * Old swap
1251		 */
1252		struct rlist *swapptr;
1253
1254		swapptr = swaplist.rlh_list;
1255		while (swapptr) {
1256			int	top, bottom, next_block;
1257
1258			KGET2(swapptr, &head, sizeof(struct rlist), "swapptr");
1259
1260			top = head.rl_end;
1261			bottom = head.rl_start;
1262
1263			nfree += top - bottom + 1;
1264
1265			/*
1266			 * Swap space is split up among the configured disks.
1267			 *
1268			 * For interleaved swap devices, the first dmmax blocks
1269			 * of swap space some from the first disk, the next
1270			 * dmmax blocks from the next, and so.
1271			 *
1272			 * The list of free space joins adjacent free blocks,
1273			 * ignoring device boundries.  If we want to keep track
1274			 * of this information per device, we'll just have to
1275			 * extract it ourselves.
1276			 */
1277			while (top / dmmax != bottom / dmmax) {
1278				next_block = ((bottom + dmmax) / dmmax);
1279				perdev[(bottom / dmmax) % nswdev] +=
1280					next_block * dmmax - bottom;
1281				bottom = next_block * dmmax;
1282			}
1283			perdev[(bottom / dmmax) % nswdev] +=
1284				top - bottom + 1;
1285
1286			swapptr = head.rl_next;
1287		}
1288	}
1289
1290	header = getbsize(&hlen, &blocksize);
1291	if (!totalflag)
1292		(void)printf("%-11s %*s %8s %8s %8s  %s\n",
1293		    "Device", hlen, header,
1294		    "Used", "Avail", "Capacity", "Type");
1295
1296	mul = 1;
1297	if (swapblist) {
1298		if ((div = blocksize / PAGE_SIZE) == 0) {
1299			mul = PAGE_SIZE / blocksize;
1300			div = 1;
1301		}
1302	} else {
1303		if ((div = blocksize / DEV_BSIZE) == 0) {
1304			mul = DEV_BSIZE / blocksize;
1305			div = 1;
1306		}
1307	}
1308
1309	avail = npfree = 0;
1310	for (i = 0; i < nswdev; i++) {
1311		int xsize, xfree;
1312
1313		/*
1314		 * Don't report statistics for partitions which have not
1315		 * yet been activated via swapon(8).
1316		 */
1317		if (!(sw[i].sw_flags & SW_FREED))
1318			continue;
1319
1320		if (!totalflag)
1321			if (sw[i].sw_dev != NODEV) {
1322				p = devname(sw[i].sw_dev, S_IFBLK);
1323				(void)printf("/dev/%-6s %*d ",
1324					     p == NULL ? "??" : p,
1325					     hlen, sw[i].sw_nblks * mul / div);
1326			} else
1327				(void)printf("[NFS swap]  %*d ",
1328					     hlen, sw[i].sw_nblks * mul / div);
1329
1330		/* The first dmmax is never allocated to avoid trashing of
1331		 * disklabels
1332		 */
1333		xsize = sw[i].sw_nblks - dmmax;
1334		xfree = perdev[i];
1335		used = xsize - xfree;
1336		npfree++;
1337		avail += xsize;
1338		if (totalflag)
1339			continue;
1340		(void)printf("%8d %8d %5.0f%%    %s\n",
1341		    used * mul / div, xfree * mul / div,
1342		    (double)used / (double)xsize * 100.0,
1343		    (sw[i].sw_flags & SW_SEQUENTIAL) ?
1344			     "Sequential" : "Interleaved");
1345	}
1346
1347	/*
1348	 * If only one partition has been set up via swapon(8), we don't
1349	 * need to bother with totals.
1350	 */
1351	used = avail - nfree;
1352	free(sw);
1353	free(perdev);
1354	if (totalflag) {
1355		(void)printf("%dM/%dM swap space\n", used / 2048, avail / 2048);
1356		return;
1357	}
1358	if (npfree > 1) {
1359		(void)printf("%-11s %*d %8d %8d %5.0f%%\n",
1360		    "Total", hlen, avail * mul / div, used * mul / div, nfree * mul / div,
1361		    (double)used / (double)avail * 100.0);
1362	}
1363}
1364