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