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