pstat.c revision 56854
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  "$FreeBSD: head/usr.sbin/pstat/pstat.c 56854 2000-01-29 16:45:28Z peter $";
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/blist.h>
71
72#include <sys/user.h>
73#include <sys/sysctl.h>
74
75#include <err.h>
76#include <fcntl.h>
77#include <kvm.h>
78#include <limits.h>
79#include <nlist.h>
80#include <stdio.h>
81#include <stdlib.h>
82#include <string.h>
83#include <unistd.h>
84
85struct nlist nl[] = {
86#define NLMANDATORYBEG	0
87#define	V_MOUNTLIST	0
88	{ "_mountlist" },	/* address of head of mount list. */
89#define V_NUMV		1
90	{ "_numvnodes" },
91#define	FNL_NFILE	2
92	{"_nfiles"},
93#define FNL_MAXFILE	3
94	{"_maxfiles"},
95#define NLMANDATORYEND FNL_MAXFILE	/* names up to here are mandatory */
96#define	SCONS		NLMANDATORYEND + 1
97	{ "_cons" },
98#define	SPTY		NLMANDATORYEND + 2
99	{ "_pt_tty" },
100#define	SNPTY		NLMANDATORYEND + 3
101	{ "_npty" },
102
103
104
105#ifdef __FreeBSD__
106#define SCCONS	(SNPTY+1)
107	{ "_sccons" },
108#define NSCCONS	(SNPTY+2)
109	{ "_nsccons" },
110#define SIO  (SNPTY+3)
111	{ "_sio_tty" },
112#define NSIO (SNPTY+4)
113	{ "_nsio_tty" },
114#define RC  (SNPTY+5)
115	{ "_rc_tty" },
116#define NRC (SNPTY+6)
117	{ "_nrc_tty" },
118#define CY  (SNPTY+7)
119	{ "_cy_tty" },
120#define NCY (SNPTY+8)
121	{ "_ncy_tty" },
122#define SI  (SNPTY+9)
123	{ "_si_tty" },
124#define NSI (SNPTY+10)
125	{ "_si_Nports" },
126#endif
127	{ "" }
128};
129
130int	usenumflag;
131int	totalflag;
132int	swapflag;
133char	*nlistf	= NULL;
134char	*memf	= NULL;
135kvm_t	*kd;
136
137char	*usagestr;
138
139struct {
140	int m_flag;
141	const char *m_name;
142} mnt_flags[] = {
143	{ MNT_RDONLY, "rdonly" },
144	{ MNT_SYNCHRONOUS, "sync" },
145	{ MNT_NOEXEC, "noexec" },
146	{ MNT_NOSUID, "nosuid" },
147	{ MNT_NODEV, "nodev" },
148	{ MNT_UNION, "union" },
149	{ MNT_ASYNC, "async" },
150	{ MNT_NOATIME, "noatime" },
151	{ MNT_EXRDONLY, "exrdonly" },
152	{ MNT_EXPORTED, "exported" },
153	{ MNT_DEFEXPORTED, "defexported" },
154	{ MNT_EXPORTANON, "exportanon" },
155	{ MNT_EXKERB, "exkerb" },
156	{ MNT_LOCAL, "local" },
157	{ MNT_QUOTA, "quota" },
158	{ MNT_ROOTFS, "rootfs" },
159	{ MNT_USER, "user" },
160	{ MNT_UPDATE, "update" },
161	{ MNT_DELEXPORT },
162	{ MNT_UPDATE, "update" },
163	{ MNT_DELEXPORT, "delexport" },
164	{ MNT_RELOAD, "reload" },
165	{ MNT_FORCE, "force" },
166#if 0
167	{ MNT_UNMOUNT, "unmount" },
168	{ MNT_MWAIT, "mwait" },
169	{ MNT_WANTRDWR, "wantrdwr" },
170#endif
171	{ 0 }
172};
173
174
175#define	SVAR(var) __STRING(var)	/* to force expansion */
176#define	KGET(idx, var)							\
177	KGET1(idx, &var, sizeof(var), SVAR(var))
178#define	KGET1(idx, p, s, msg)						\
179	KGET2(nl[idx].n_value, p, s, msg)
180#define	KGET2(addr, p, s, msg)						\
181	if (kvm_read(kd, (u_long)(addr), p, s) != s)			\
182		warnx("cannot read %s: %s", msg, kvm_geterr(kd))
183#define	KGETN(idx, var)							\
184	KGET1N(idx, &var, sizeof(var), SVAR(var))
185#define	KGET1N(idx, p, s, msg)						\
186	KGET2N(nl[idx].n_value, p, s, msg)
187#define	KGET2N(addr, p, s, msg)						\
188	((kvm_read(kd, (u_long)(addr), p, s) == s) ? 1 : 0)
189#define	KGETRET(addr, p, s, msg)					\
190	if (kvm_read(kd, (u_long)(addr), p, s) != s) {			\
191		warnx("cannot read %s: %s", msg, kvm_geterr(kd));	\
192		return (0);						\
193	}
194
195void	filemode __P((void));
196int	getfiles __P((char **, int *));
197struct mount *
198	getmnt __P((struct mount *));
199struct e_vnode *
200	kinfo_vnodes __P((int *));
201struct e_vnode *
202	loadvnodes __P((int *));
203void	mount_print __P((struct mount *));
204void	nfs_header __P((void));
205int	nfs_print __P((struct vnode *));
206void	swapmode __P((void));
207void	ttymode __P((void));
208void	ttyprt __P((struct tty *, int));
209void	ttytype __P((struct tty *, char *, int, int, int));
210void	ufs_header __P((void));
211int	ufs_print __P((struct vnode *));
212void	union_header __P((void));
213int	union_print __P((struct vnode *));
214static void usage __P((void));
215void	vnode_header __P((void));
216void	vnode_print __P((struct vnode *, struct vnode *));
217void	vnodemode __P((void));
218
219int
220main(argc, argv)
221	int argc;
222	char *argv[];
223{
224	int ch, i, quit, ret;
225	int fileflag, ttyflag, vnodeflag;
226	char buf[_POSIX2_LINE_MAX],*opts;
227
228	fileflag = swapflag = ttyflag = vnodeflag = 0;
229
230	/* We will behave like good old swapinfo if thus invoked */
231	opts = strrchr(argv[0],'/');
232	if (opts)
233		opts++;
234	else
235		opts = argv[0];
236	if (!strcmp(opts,"swapinfo")) {
237		swapflag = 1;
238		opts = "kM:N:";
239		usagestr = "swapinfo [-k] [-M core] [-N system]";
240	} else {
241		opts = "TM:N:fiknstv";
242		usagestr = "pstat [-Tfknstv] [-M core] [-N system]";
243	}
244
245	while ((ch = getopt(argc, argv, opts)) != -1)
246		switch (ch) {
247		case 'f':
248			fileflag = 1;
249			break;
250		case 'k':
251			putenv("BLOCKSIZE=1K");
252			break;
253		case 'M':
254			memf = optarg;
255			break;
256		case 'N':
257			nlistf = optarg;
258			break;
259		case 'n':
260			usenumflag = 1;
261			break;
262		case 's':
263			++swapflag;
264			break;
265		case 'T':
266			totalflag = 1;
267			break;
268		case 't':
269			ttyflag = 1;
270			break;
271		case 'v':
272		case 'i':		/* Backward compatibility. */
273			errx(1, "vnode mode not supported");
274#if 0
275			vnodeflag = 1;
276			break;
277#endif
278		default:
279			usage();
280		}
281	argc -= optind;
282	argv += optind;
283
284	/*
285	 * Discard setgid privileges if not the running kernel so that bad
286	 * guys can't print interesting stuff from kernel memory.
287	 */
288	if (nlistf != NULL || memf != NULL)
289		(void)setgid(getgid());
290
291	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, buf)) == 0)
292		errx(1, "kvm_openfiles: %s", buf);
293	if ((ret = kvm_nlist(kd, nl)) != 0) {
294		if (ret == -1)
295			errx(1, "kvm_nlist: %s", kvm_geterr(kd));
296		for (i = NLMANDATORYBEG, quit = 0; i <= NLMANDATORYEND; i++)
297			if (!nl[i].n_value) {
298				quit = 1;
299				warnx("undefined symbol: %s", nl[i].n_name);
300			}
301		if (quit)
302			exit(1);
303	}
304	if (!(fileflag | vnodeflag | ttyflag | swapflag | totalflag))
305		usage();
306	if (fileflag || totalflag)
307		filemode();
308	if (vnodeflag)
309		vnodemode();
310	if (ttyflag)
311		ttymode();
312	if (swapflag || totalflag)
313		swapmode();
314	exit (0);
315}
316
317static void
318usage()
319{
320	fprintf(stderr, "usage: %s\n", usagestr);
321	exit (1);
322}
323
324struct e_vnode {
325	struct vnode *avnode;
326	struct vnode vnode;
327};
328
329void
330vnodemode()
331{
332	struct e_vnode *e_vnodebase, *endvnode, *evp;
333	struct vnode *vp;
334	struct mount *maddr, *mp;
335	int numvnodes;
336
337	e_vnodebase = loadvnodes(&numvnodes);
338	if (totalflag) {
339		(void)printf("%7d vnodes\n", numvnodes);
340		return;
341	}
342	endvnode = e_vnodebase + numvnodes;
343	(void)printf("%d active vnodes\n", numvnodes);
344
345
346#define ST	mp->mnt_stat
347	maddr = NULL;
348	for (evp = e_vnodebase; evp < endvnode; evp++) {
349		vp = &evp->vnode;
350		if (vp->v_mount != maddr) {
351			/*
352			 * New filesystem
353			 */
354			if ((mp = getmnt(vp->v_mount)) == NULL)
355				continue;
356			maddr = vp->v_mount;
357			mount_print(mp);
358			vnode_header();
359			if (!strcmp(ST.f_fstypename, "ufs") ||
360			    !strcmp(ST.f_fstypename, "mfs"))
361				ufs_header();
362			else if (!strcmp(ST.f_fstypename, "nfs"))
363				nfs_header();
364			else if (!strcmp(ST.f_fstypename, "union"))
365				union_header();
366			(void)printf("\n");
367		}
368		vnode_print(evp->avnode, vp);
369		if (!strcmp(ST.f_fstypename, "ufs") ||
370		    !strcmp(ST.f_fstypename, "mfs"))
371			ufs_print(vp);
372		else if (!strcmp(ST.f_fstypename, "nfs"))
373			nfs_print(vp);
374		else if (!strcmp(ST.f_fstypename, "union"))
375			union_print(vp);
376		(void)printf("\n");
377	}
378	free(e_vnodebase);
379}
380
381void
382vnode_header()
383{
384	(void)printf("ADDR     TYP VFLAG  USE HOLD");
385}
386
387void
388vnode_print(avnode, vp)
389	struct vnode *avnode;
390	struct vnode *vp;
391{
392	char *type, flags[16];
393	char *fp = flags;
394	int flag;
395
396	/*
397	 * set type
398	 */
399	switch (vp->v_type) {
400	case VNON:
401		type = "non"; break;
402	case VREG:
403		type = "reg"; break;
404	case VDIR:
405		type = "dir"; break;
406	case VBLK:
407		type = "blk"; break;
408	case VCHR:
409		type = "chr"; break;
410	case VLNK:
411		type = "lnk"; break;
412	case VSOCK:
413		type = "soc"; break;
414	case VFIFO:
415		type = "fif"; break;
416	case VBAD:
417		type = "bad"; break;
418	default:
419		type = "unk"; break;
420	}
421	/*
422	 * gather flags
423	 */
424	flag = vp->v_flag;
425	if (flag & VROOT)
426		*fp++ = 'R';
427	if (flag & VTEXT)
428		*fp++ = 'T';
429	if (flag & VSYSTEM)
430		*fp++ = 'S';
431	if (flag & VISTTY)
432		*fp++ = 't';
433	if (flag & VXLOCK)
434		*fp++ = 'L';
435	if (flag & VXWANT)
436		*fp++ = 'W';
437	if (flag & VBWAIT)
438		*fp++ = 'B';
439	if (flag & VOBJBUF)
440		*fp++ = 'V';
441	if (flag & VAGE)
442		*fp++ = 'a';
443	if (flag & VOLOCK)
444		*fp++ = 'l';
445	if (flag & VOWANT)
446		*fp++ = 'w';
447	if (flag == 0)
448		*fp++ = '-';
449	*fp = '\0';
450	(void)printf("%8lx %s %5s %4d %4d",
451	    (u_long)(void *)avnode, type, flags, vp->v_usecount, vp->v_holdcnt);
452}
453
454void
455ufs_header()
456{
457	(void)printf(" FILEID IFLAG RDEV|SZ");
458}
459
460int
461ufs_print(vp)
462	struct vnode *vp;
463{
464	int flag;
465	struct inode inode, *ip = &inode;
466	char flagbuf[16], *flags = flagbuf;
467	char *name;
468	mode_t type;
469
470	KGETRET(VTOI(vp), &inode, sizeof(struct inode), "vnode's inode");
471	flag = ip->i_flag;
472	if (flag & IN_RENAME)
473		*flags++ = 'R';
474	if (flag & IN_UPDATE)
475		*flags++ = 'U';
476	if (flag & IN_ACCESS)
477		*flags++ = 'A';
478	if (flag & IN_CHANGE)
479		*flags++ = 'C';
480	if (flag & IN_MODIFIED)
481		*flags++ = 'M';
482	if (flag & IN_SHLOCK)
483		*flags++ = 'S';
484	if (flag & IN_EXLOCK)
485		*flags++ = 'E';
486	if (flag == 0)
487		*flags++ = '-';
488	*flags = '\0';
489
490	(void)printf(" %6d %5s", ip->i_number, flagbuf);
491	type = ip->i_mode & S_IFMT;
492	if (S_ISCHR(ip->i_mode) || S_ISBLK(ip->i_mode))
493		if (usenumflag || ((name = devname(ip->i_rdev, type)) == NULL))
494			(void)printf("   %2d,%-2d",
495			    major(ip->i_rdev), minor(ip->i_rdev));
496		else
497			(void)printf(" %7s", name);
498	else
499		(void)printf(" %7qd", ip->i_size);
500	return (0);
501}
502
503void
504nfs_header()
505{
506	(void)printf(" FILEID NFLAG RDEV|SZ");
507}
508
509int
510nfs_print(vp)
511	struct vnode *vp;
512{
513	struct nfsnode nfsnode, *np = &nfsnode;
514	char flagbuf[16], *flags = flagbuf;
515	int flag;
516	char *name;
517	mode_t type;
518
519	KGETRET(VTONFS(vp), &nfsnode, sizeof(nfsnode), "vnode's nfsnode");
520	flag = np->n_flag;
521	if (flag & NFLUSHWANT)
522		*flags++ = 'W';
523	if (flag & NFLUSHINPROG)
524		*flags++ = 'P';
525	if (flag & NMODIFIED)
526		*flags++ = 'M';
527	if (flag & NWRITEERR)
528		*flags++ = 'E';
529	if (flag & NQNFSNONCACHE)
530		*flags++ = 'X';
531	if (flag & NQNFSWRITE)
532		*flags++ = 'O';
533	if (flag & NQNFSEVICTED)
534		*flags++ = 'G';
535	if (flag == 0)
536		*flags++ = '-';
537	*flags = '\0';
538
539#define VT	np->n_vattr
540	(void)printf(" %6ld %5s", VT.va_fileid, flagbuf);
541	type = VT.va_mode & S_IFMT;
542	if (S_ISCHR(VT.va_mode) || S_ISBLK(VT.va_mode))
543		if (usenumflag || ((name = devname(VT.va_rdev, type)) == NULL))
544			(void)printf("   %2d,%-2d",
545			    major(VT.va_rdev), minor(VT.va_rdev));
546		else
547			(void)printf(" %7s", name);
548	else
549		(void)printf(" %7qd", np->n_size);
550	return (0);
551}
552
553void
554union_header()
555{
556	(void)printf("    UPPER    LOWER");
557}
558
559int
560union_print(vp)
561	struct vnode *vp;
562{
563	struct union_node unode, *up = &unode;
564
565	KGETRET(VTOUNION(vp), &unode, sizeof(unode), "vnode's unode");
566
567	(void)printf(" %8lx %8lx", (u_long)(void *)up->un_uppervp,
568	    (u_long)(void *)up->un_lowervp);
569	return (0);
570}
571
572/*
573 * Given a pointer to a mount structure in kernel space,
574 * read it in and return a usable pointer to it.
575 */
576struct mount *
577getmnt(maddr)
578	struct mount *maddr;
579{
580	static struct mtab {
581		struct mtab *next;
582		struct mount *maddr;
583		struct mount mount;
584	} *mhead = NULL;
585	struct mtab *mt;
586
587	for (mt = mhead; mt != NULL; mt = mt->next)
588		if (maddr == mt->maddr)
589			return (&mt->mount);
590	if ((mt = malloc(sizeof(struct mtab))) == NULL)
591		errx(1, "malloc");
592	KGETRET(maddr, &mt->mount, sizeof(struct mount), "mount table");
593	mt->maddr = maddr;
594	mt->next = mhead;
595	mhead = mt;
596	return (&mt->mount);
597}
598
599void
600mount_print(mp)
601	struct mount *mp;
602{
603	int flags;
604	const char *type;
605
606#define ST	mp->mnt_stat
607	(void)printf("*** MOUNT %s %s on %s", ST.f_fstypename,
608	    ST.f_mntfromname, ST.f_mntonname);
609	if ((flags = mp->mnt_flag)) {
610		int i;
611		const char *sep = " (";
612
613		for (i = 0; mnt_flags[i].m_flag; i++) {
614			if (flags & mnt_flags[i].m_flag) {
615				(void)printf("%s%s", sep, mnt_flags[i].m_name);
616				flags &= ~mnt_flags[i].m_flag;
617				sep = ",";
618			}
619		}
620		if (flags)
621			(void)printf("%sunknown_flags:%x", sep, flags);
622		(void)printf(")");
623	}
624	(void)printf("\n");
625#undef ST
626}
627
628struct e_vnode *
629loadvnodes(avnodes)
630	int *avnodes;
631{
632	int mib[2];
633	size_t copysize;
634	struct e_vnode *vnodebase;
635
636	if (memf != NULL) {
637		/*
638		 * do it by hand
639		 */
640		return (kinfo_vnodes(avnodes));
641	}
642	mib[0] = CTL_KERN;
643	mib[1] = KERN_VNODE;
644	if (sysctl(mib, 2, NULL, &copysize, NULL, 0) == -1)
645		err(1, "sysctl: KERN_VNODE");
646	if ((vnodebase = malloc(copysize)) == NULL)
647		errx(1, "malloc");
648	if (sysctl(mib, 2, vnodebase, &copysize, NULL, 0) == -1)
649		err(1, "sysctl: KERN_VNODE");
650	if (copysize % sizeof(struct e_vnode))
651		errx(1, "vnode size mismatch");
652	*avnodes = copysize / sizeof(struct e_vnode);
653
654	return (vnodebase);
655}
656
657/*
658 * simulate what a running kernel does in in kinfo_vnode
659 */
660struct e_vnode *
661kinfo_vnodes(avnodes)
662	int *avnodes;
663{
664	struct mntlist mountlist;
665	struct mount *mp, mount, *mp_next;
666	struct vnode *vp, vnode, *vp_next;
667	char *vbuf, *evbuf, *bp;
668	int num, numvnodes;
669
670#define VPTRSZ  sizeof(struct vnode *)
671#define VNODESZ sizeof(struct vnode)
672
673	KGET(V_NUMV, numvnodes);
674	if ((vbuf = malloc((numvnodes + 20) * (VPTRSZ + VNODESZ))) == NULL)
675		errx(1, "malloc");
676	bp = vbuf;
677	evbuf = vbuf + (numvnodes + 20) * (VPTRSZ + VNODESZ);
678	KGET(V_MOUNTLIST, mountlist);
679	for (num = 0, mp = TAILQ_FIRST(&mountlist); ; mp = mp_next) {
680		KGET2(mp, &mount, sizeof(mount), "mount entry");
681		mp_next = TAILQ_NEXT(&mount, mnt_list);
682		for (vp = mount.mnt_vnodelist.lh_first;
683		    vp != NULL; vp = vp_next) {
684			KGET2(vp, &vnode, sizeof(vnode), "vnode");
685			vp_next = vnode.v_mntvnodes.le_next;
686			if ((bp + VPTRSZ + VNODESZ) > evbuf)
687				/* XXX - should realloc */
688				errx(1, "no more room for vnodes");
689			memmove(bp, &vp, VPTRSZ);
690			bp += VPTRSZ;
691			memmove(bp, &vnode, VNODESZ);
692			bp += VNODESZ;
693			num++;
694		}
695		if (mp == TAILQ_LAST(&mountlist, mntlist))
696			break;
697	}
698	*avnodes = num;
699	return ((struct e_vnode *)vbuf);
700}
701
702char hdr[] =
703"  LINE RAW CAN OUT IHIWT ILOWT OHWT LWT     COL STATE  SESS      PGID DISC\n";
704int ttyspace = 128;
705
706void
707ttymode()
708{
709	struct tty *tty;
710	struct tty ttyb[1000];
711	int error, len, i;
712
713	(void)printf(hdr);
714	len = sizeof(ttyb);
715	error = sysctlbyname("kern.ttys", &ttyb, &len, 0, 0);
716	if (!error) {
717		len /= sizeof(ttyb[0]);
718		for (i = 0; i < len; i++) {
719			ttyprt(&ttyb[i], 0);
720		}
721	}
722	if ((tty = malloc(ttyspace * sizeof(*tty))) == NULL)
723		errx(1, "malloc");
724	if (nl[SCONS].n_type != 0) {
725		(void)printf("1 console\n");
726		KGET(SCONS, *tty);
727		ttyprt(&tty[0], 0);
728	}
729#ifdef __FreeBSD__
730	if (nl[NSCCONS].n_type != 0)
731		ttytype(tty, "vty", SCCONS, NSCCONS, 0);
732	if (nl[NSIO].n_type != 0)
733		ttytype(tty, "sio", SIO, NSIO, 0);
734	if (nl[NRC].n_type != 0)
735		ttytype(tty, "rc", RC, NRC, 0);
736	if (nl[NCY].n_type != 0)
737		ttytype(tty, "cy", CY, NCY, 0);
738	if (nl[NSI].n_type != 0)
739		ttytype(tty, "si", SI, NSI, 1);
740#endif
741	if (nl[SNPTY].n_type != 0)
742		ttytype(tty, "pty", SPTY, SNPTY, 0);
743}
744
745void
746ttytype(tty, name, type, number, indir)
747	struct tty *tty;
748	char *name;
749	int type, number, indir;
750{
751	struct tty *tp;
752	int ntty;
753	struct tty **ttyaddr;
754
755	if (tty == NULL)
756		return;
757	KGET(number, ntty);
758	(void)printf("%d %s %s\n", ntty, name, (ntty == 1) ? "line" : "lines");
759	if (ntty > ttyspace) {
760		ttyspace = ntty;
761		if ((tty = realloc(tty, ttyspace * sizeof(*tty))) == 0)
762			errx(1, "realloc");
763	}
764	if (indir) {
765		KGET(type, ttyaddr);
766		KGET2(ttyaddr, tty, ntty * sizeof(struct tty), "tty structs");
767	} else {
768		KGET1(type, tty, ntty * sizeof(struct tty), "tty structs");
769	}
770	(void)printf(hdr);
771	for (tp = tty; tp < &tty[ntty]; tp++)
772		ttyprt(tp, tp - tty);
773}
774
775struct {
776	int flag;
777	char val;
778} ttystates[] = {
779#ifdef TS_WOPEN
780	{ TS_WOPEN,	'W'},
781#endif
782	{ TS_ISOPEN,	'O'},
783	{ TS_CARR_ON,	'C'},
784#ifdef TS_CONNECTED
785	{ TS_CONNECTED,	'c'},
786#endif
787	{ TS_TIMEOUT,	'T'},
788	{ TS_FLUSH,	'F'},
789	{ TS_BUSY,	'B'},
790#ifdef TS_ASLEEP
791	{ TS_ASLEEP,	'A'},
792#endif
793#ifdef TS_SO_OLOWAT
794	{ TS_SO_OLOWAT,	'A'},
795#endif
796#ifdef TS_SO_OCOMPLETE
797	{ TS_SO_OCOMPLETE, 'a'},
798#endif
799	{ TS_XCLUDE,	'X'},
800	{ TS_TTSTOP,	'S'},
801#ifdef TS_CAR_OFLOW
802	{ TS_CAR_OFLOW,	'm'},
803#endif
804#ifdef TS_CTS_OFLOW
805	{ TS_CTS_OFLOW,	'o'},
806#endif
807#ifdef TS_DSR_OFLOW
808	{ TS_DSR_OFLOW,	'd'},
809#endif
810	{ TS_TBLOCK,	'K'},
811	{ TS_ASYNC,	'Y'},
812	{ TS_BKSL,	'D'},
813	{ TS_ERASE,	'E'},
814	{ TS_LNCH,	'L'},
815	{ TS_TYPEN,	'P'},
816	{ TS_CNTTB,	'N'},
817#ifdef TS_CAN_BYPASS_L_RINT
818	{ TS_CAN_BYPASS_L_RINT, 'l'},
819#endif
820#ifdef TS_SNOOP
821	{ TS_SNOOP,     's'},
822#endif
823#ifdef TS_ZOMBIE
824	{ TS_ZOMBIE,	'Z'},
825#endif
826	{ 0,	       '\0'},
827};
828
829void
830ttyprt(tp, line)
831	struct tty *tp;
832	int line;
833{
834	int i, j;
835	pid_t pgid;
836	char *name, state[20];
837
838	if (usenumflag || tp->t_dev == 0 ||
839	   (name = devname(tp->t_dev, S_IFCHR)) == NULL)
840		(void)printf("%7d ", line);
841	else
842		(void)printf("%7s ", name);
843	(void)printf("%2d %3d ", tp->t_rawq.c_cc, tp->t_canq.c_cc);
844	(void)printf("%3d %5d %5d %4d %3d %7d ", tp->t_outq.c_cc,
845		tp->t_ihiwat, tp->t_ilowat, tp->t_ohiwat, tp->t_olowat,
846		tp->t_column);
847	for (i = j = 0; ttystates[i].flag; i++)
848		if (tp->t_state&ttystates[i].flag)
849			state[j++] = ttystates[i].val;
850	if (j == 0)
851		state[j++] = '-';
852	state[j] = '\0';
853	(void)printf("%-6s %8lx", state, (u_long)(void *)tp->t_session);
854	pgid = 0;
855	if (tp->t_pgrp != NULL)
856		KGET2(&tp->t_pgrp->pg_id, &pgid, sizeof(pid_t), "pgid");
857	(void)printf("%6d ", pgid);
858	switch (tp->t_line) {
859	case TTYDISC:
860		(void)printf("term\n");
861		break;
862	case NTTYDISC:
863		(void)printf("ntty\n");
864		break;
865	case SLIPDISC:
866		(void)printf("slip\n");
867		break;
868	case PPPDISC:
869		(void)printf("ppp\n");
870		break;
871	default:
872		(void)printf("%d\n", tp->t_line);
873		break;
874	}
875}
876
877void
878filemode()
879{
880	struct file *fp;
881	struct file *addr;
882	char *buf, flagbuf[16], *fbp;
883	int len, maxfile, nfile;
884	static char *dtypes[] = { "???", "inode", "socket" };
885
886	KGET(FNL_MAXFILE, maxfile);
887	if (totalflag) {
888		KGET(FNL_NFILE, nfile);
889		(void)printf("%3d/%3d files\n", nfile, maxfile);
890		return;
891	}
892	if (getfiles(&buf, &len) == -1)
893		return;
894	/*
895	 * Getfiles returns in malloc'd memory a pointer to the first file
896	 * structure, and then an array of file structs (whose addresses are
897	 * derivable from the previous entry).
898	 */
899	addr = ((struct filelist *)buf)->lh_first;
900	fp = (struct file *)(buf + sizeof(struct filelist));
901	nfile = (len - sizeof(struct filelist)) / sizeof(struct file);
902
903	(void)printf("%d/%d open files\n", nfile, maxfile);
904	(void)printf("   LOC   TYPE    FLG     CNT  MSG    DATA    OFFSET\n");
905	for (; (char *)fp < buf + len; addr = fp->f_list.le_next, fp++) {
906		if ((unsigned)fp->f_type > DTYPE_SOCKET)
907			continue;
908		(void)printf("%8lx ", (u_long)(void *)addr);
909		(void)printf("%-8.8s", dtypes[fp->f_type]);
910		fbp = flagbuf;
911		if (fp->f_flag & FREAD)
912			*fbp++ = 'R';
913		if (fp->f_flag & FWRITE)
914			*fbp++ = 'W';
915		if (fp->f_flag & FAPPEND)
916			*fbp++ = 'A';
917#ifdef FSHLOCK	/* currently gone */
918		if (fp->f_flag & FSHLOCK)
919			*fbp++ = 'S';
920		if (fp->f_flag & FEXLOCK)
921			*fbp++ = 'X';
922#endif
923		if (fp->f_flag & FASYNC)
924			*fbp++ = 'I';
925		*fbp = '\0';
926		(void)printf("%6s  %3d", flagbuf, fp->f_count);
927		(void)printf("  %3d", fp->f_msgcount);
928		(void)printf("  %8lx", (u_long)(void *)fp->f_data);
929		if (fp->f_offset < 0)
930			(void)printf("  %qx\n", fp->f_offset);
931		else
932			(void)printf("  %qd\n", fp->f_offset);
933	}
934	free(buf);
935}
936
937int
938getfiles(abuf, alen)
939	char **abuf;
940	int *alen;
941{
942	size_t len;
943	int mib[2];
944	char *buf;
945
946	/*
947	 * XXX
948	 * Add emulation of KINFO_FILE here.
949	 */
950	if (memf != NULL)
951		errx(1, "files on dead kernel, not implemented");
952
953	mib[0] = CTL_KERN;
954	mib[1] = KERN_FILE;
955	if (sysctl(mib, 2, NULL, &len, NULL, 0) == -1) {
956		warn("sysctl: KERN_FILE");
957		return (-1);
958	}
959	if ((buf = malloc(len)) == NULL)
960		errx(1, "malloc");
961	if (sysctl(mib, 2, buf, &len, NULL, 0) == -1) {
962		warn("sysctl: KERN_FILE");
963		return (-1);
964	}
965	*abuf = buf;
966	*alen = len;
967	return (0);
968}
969
970/*
971 * swapmode is based on a program called swapinfo written
972 * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
973 */
974void
975swapmode(void)
976{
977	struct kvm_swap kswap[16];
978	int i;
979	int n;
980	int pagesize = getpagesize();
981	const char *header;
982	int hlen;
983	long blocksize;
984
985	n = kvm_getswapinfo(
986	    kd,
987	    kswap,
988	    sizeof(kswap)/sizeof(kswap[0]),
989	    ((swapflag > 1) ? SWIF_DUMP_TREE : 0) | SWIF_DEV_PREFIX
990	);
991
992#define CONVERT(v)	((int)((quad_t)(v) * pagesize / blocksize))
993
994	header = getbsize(&hlen, &blocksize);
995	if (totalflag == 0) {
996		(void)printf("%-15s %*s %8s %8s %8s  %s\n",
997		    "Device", hlen, header,
998		    "Used", "Avail", "Capacity", "Type");
999
1000		for (i = 0; i < n; ++i) {
1001			(void)printf(
1002			    "%-15s %*d ",
1003			    kswap[i].ksw_devname,
1004			    hlen,
1005			    CONVERT(kswap[i].ksw_total)
1006			);
1007			(void)printf(
1008			    "%8d %8d %5.0f%%    %s\n",
1009			    CONVERT(kswap[i].ksw_used),
1010			    CONVERT(kswap[i].ksw_total - kswap[i].ksw_used),
1011			    (double)kswap[i].ksw_used * 100.0 /
1012				(double)kswap[i].ksw_total,
1013			    (kswap[i].ksw_flags & SW_SEQUENTIAL) ?
1014				"Sequential" : "Interleaved"
1015			);
1016		}
1017	}
1018
1019	if (totalflag) {
1020		blocksize = 1024 * 1024;
1021
1022		(void)printf(
1023		    "%dM/%dM swap space\n",
1024		    CONVERT(kswap[n].ksw_used),
1025		    CONVERT(kswap[n].ksw_total)
1026		);
1027	} else if (n > 1) {
1028		(void)printf(
1029		    "%-15s %*d %8d %8d %5.0f%%\n",
1030		    "Total",
1031		    hlen,
1032		    CONVERT(kswap[n].ksw_total),
1033		    CONVERT(kswap[n].ksw_used),
1034		    CONVERT(kswap[n].ksw_total - kswap[n].ksw_used),
1035		    (double)kswap[n].ksw_used * 100.0 /
1036			(double)kswap[n].ksw_total
1037		);
1038	}
1039}
1040