xref: /freebsd/usr.sbin/pstat/pstat.c (revision df7f5d4de4592a8948a25ce01e5bddfbb7ce39dc)
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
35 static 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 static char sccsid[] = "@(#)pstat.c	8.16 (Berkeley) 5/9/95";
42 #endif /* not lint */
43 
44 #include <sys/param.h>
45 #include <sys/time.h>
46 #include <sys/vnode.h>
47 #include <sys/ucred.h>
48 #define KERNEL
49 #include <sys/file.h>
50 #include <ufs/ufs/quota.h>
51 #include <ufs/ufs/inode.h>
52 #define NFS
53 #include <sys/mount.h>
54 #undef NFS
55 #include <sys/uio.h>
56 #include <sys/namei.h>
57 #include <miscfs/union/union.h>
58 #undef KERNEL
59 #include <sys/stat.h>
60 #include <nfs/rpcv2.h>
61 #include <nfs/nfsproto.h>
62 #define KERNEL
63 #include <nfs/nfs.h>
64 #undef KERNEL
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 
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 
85 struct nlist nl[] = {
86 #define VM_SWAPLIST	0
87 	{ "_swaplist" },/* list of free swap areas */
88 #define VM_SWDEVT	1
89 	{ "_swdevt" },	/* list of swap devices and sizes */
90 #define VM_NSWAP	2
91 	{ "_nswap" },	/* size of largest swap device */
92 #define VM_NSWDEV	3
93 	{ "_nswdev" },	/* number of swap devices */
94 #define VM_DMMAX	4
95 	{ "_dmmax" },	/* maximum size of a swap block */
96 #define	V_MOUNTLIST	5
97 	{ "_mountlist" },	/* address of head of mount list. */
98 #define V_NUMV		6
99 	{ "_numvnodes" },
100 #define	FNL_NFILE	7
101 	{"_nfiles"},
102 #define FNL_MAXFILE	8
103 	{"_maxfiles"},
104 #define NLMANDATORY FNL_MAXFILE	/* names up to here are mandatory */
105 #define	SCONS		NLMANDATORY + 1
106 	{ "_cons" },
107 #define	SPTY		NLMANDATORY + 2
108 	{ "_pt_tty" },
109 #define	SNPTY		NLMANDATORY + 3
110 	{ "_npty" },
111 
112 #ifdef hp300
113 #define	SDCA	(SNPTY+1)
114 	{ "_dca_tty" },
115 #define	SNDCA	(SNPTY+2)
116 	{ "_ndca" },
117 #define	SDCM	(SNPTY+3)
118 	{ "_dcm_tty" },
119 #define	SNDCM	(SNPTY+4)
120 	{ "_ndcm" },
121 #define	SDCL	(SNPTY+5)
122 	{ "_dcl_tty" },
123 #define	SNDCL	(SNPTY+6)
124 	{ "_ndcl" },
125 #define	SITE	(SNPTY+7)
126 	{ "_ite_tty" },
127 #define	SNITE	(SNPTY+8)
128 	{ "_nite" },
129 #endif
130 
131 #ifdef mips
132 #define SDC	(SNPTY+1)
133 	{ "_dc_tty" },
134 #define SNDC	(SNPTY+2)
135 	{ "_dc_cnt" },
136 #endif
137 
138 #ifdef __FreeBSD__
139 #define SCCONS	(SNPTY+1)
140 	{ "_sccons" },
141 #define NSCCONS	(SNPTY+2)
142 	{ "_nsccons" },
143 #define SIO  (SNPTY+3)
144 	{ "_sio_tty" },
145 #define NSIO (SNPTY+4)
146 	{ "_nsio_tty" },
147 #define RC  (SNPTY+5)
148 	{ "_rc_tty" },
149 #define NRC (SNPTY+6)
150 	{ "_nrc_tty" },
151 #define CY  (SNPTY+7)
152 	{ "_cy_tty" },
153 #define NCY (SNPTY+8)
154 	{ "_ncy_tty" },
155 #define SI  (SNPTY+9)
156 	{ "_si_tty" },
157 #define NSI (SNPTY+10)
158 	{ "_si_Nports" },
159 #endif
160 	{ "" }
161 };
162 
163 int	usenumflag;
164 int	totalflag;
165 char	*nlistf	= NULL;
166 char	*memf	= NULL;
167 kvm_t	*kd;
168 
169 char	*usage;
170 
171 struct {
172 	int m_flag;
173 	const char *m_name;
174 } mnt_flags[] = {
175 	{ MNT_RDONLY, "rdonly" },
176 	{ MNT_SYNCHRONOUS, "sync" },
177 	{ MNT_NOEXEC, "noexec" },
178 	{ MNT_NOSUID, "nosuid" },
179 	{ MNT_NODEV, "nodev" },
180 	{ MNT_UNION, "union" },
181 	{ MNT_ASYNC, "async" },
182 	{ MNT_EXRDONLY, "exrdonly" },
183 	{ MNT_EXPORTED, "exported" },
184 	{ MNT_DEFEXPORTED, "defexported" },
185 	{ MNT_EXPORTANON, "exportanon" },
186 	{ MNT_EXKERB, "exkerb" },
187 	{ MNT_LOCAL, "local" },
188 	{ MNT_QUOTA, "quota" },
189 	{ MNT_ROOTFS, "rootfs" },
190 	{ MNT_UPDATE, "update" },
191 	{ MNT_DELEXPORT },
192 	{ MNT_UPDATE, "update" },
193 	{ MNT_DELEXPORT, "delexport" },
194 	{ MNT_RELOAD, "reload" },
195 	{ MNT_FORCE, "force" },
196 #if 0
197 	{ MNT_MLOCK, "mlock" },
198 #endif
199 	{ MNT_WAIT, "wait" },
200 #if 0
201 	{ MNT_MPBUSY, "mpbusy" },
202 	{ MNT_MPWANT, "mpwant" },
203 #endif
204 	{ MNT_UNMOUNT, "unmount" },
205 	{ MNT_WANTRDWR, "wantrdwr" },
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	KGETRET(addr, p, s, msg)					\
219 	if (kvm_read(kd, (u_long)(addr), p, s) != s) {			\
220 		warnx("cannot read %s: %s", msg, kvm_geterr(kd));	\
221 		return (0);						\
222 	}
223 
224 void	filemode __P((void));
225 int	getfiles __P((char **, int *));
226 struct mount *
227 	getmnt __P((struct mount *));
228 struct e_vnode *
229 	kinfo_vnodes __P((int *));
230 struct e_vnode *
231 	loadvnodes __P((int *));
232 void	mount_print __P((struct mount *));
233 void	nfs_header __P((void));
234 int	nfs_print __P((struct vnode *));
235 void	swapmode __P((void));
236 void	ttymode __P((void));
237 void	ttyprt __P((struct tty *, int));
238 void	ttytype __P((struct tty *, char *, int, int, int));
239 void	ufs_header __P((void));
240 int	ufs_print __P((struct vnode *));
241 void	union_header __P((void));
242 int	union_print __P((struct vnode *));
243 void	vnode_header __P((void));
244 void	vnode_print __P((struct vnode *, struct vnode *));
245 void	vnodemode __P((void));
246 
247 int
248 main(argc, argv)
249 	int argc;
250 	char *argv[];
251 {
252 	extern char *optarg;
253 	extern int optind;
254 	int ch, i, quit, ret;
255 	int fileflag, swapflag, ttyflag, vnodeflag;
256 	char buf[_POSIX2_LINE_MAX],*opts;
257 
258 	fileflag = swapflag = ttyflag = vnodeflag = 0;
259 
260 	/* We will behave like good old swapinfo if thus invoked */
261 	opts = strrchr(argv[0],'/');
262 	if (opts)
263 		opts++;
264 	else
265 		opts = argv[0];
266 	if (!strcmp(opts,"swapinfo")) {
267 		swapflag = 1;
268 		opts = "kM:N:";
269 		usage = "usage: swapinfo [-k] [-M core] [-N system]\n";
270 	} else {
271 		opts = "TM:N:fiknstv";
272 		usage = "usage: pstat [-Tfknstv] [-M core] [-N system]\n";
273 	}
274 
275 	while ((ch = getopt(argc, argv, opts)) != EOF)
276 		switch (ch) {
277 		case 'f':
278 			fileflag = 1;
279 			break;
280 		case 'k':
281 			putenv("BLOCKSIZE=1K");
282 			break;
283 		case 'M':
284 			memf = optarg;
285 			break;
286 		case 'N':
287 			nlistf = optarg;
288 			break;
289 		case 'n':
290 			usenumflag = 1;
291 			break;
292 		case 's':
293 			swapflag = 1;
294 			break;
295 		case 'T':
296 			totalflag = 1;
297 			break;
298 		case 't':
299 			ttyflag = 1;
300 			break;
301 		case 'v':
302 		case 'i':		/* Backward compatibility. */
303 			vnodeflag = 1;
304 			break;
305 		default:
306 			(void)fprintf(stderr, usage);
307 			exit(1);
308 		}
309 	argc -= optind;
310 	argv += optind;
311 
312 	/*
313 	 * Discard setgid privileges if not the running kernel so that bad
314 	 * guys can't print interesting stuff from kernel memory.
315 	 */
316 	if (nlistf != NULL || memf != NULL)
317 		(void)setgid(getgid());
318 
319 	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, buf)) == 0)
320 		errx(1, "kvm_openfiles: %s", buf);
321 	if ((ret = kvm_nlist(kd, nl)) != 0) {
322 		if (ret == -1)
323 			errx(1, "kvm_nlist: %s", kvm_geterr(kd));
324 		for (i = quit = 0; i <= NLMANDATORY; i++)
325 			if (!nl[i].n_value) {
326 				quit = 1;
327 				warnx("undefined symbol: %s\n", nl[i].n_name);
328 			}
329 		if (quit)
330 			exit(1);
331 	}
332 	if (!(fileflag | vnodeflag | ttyflag | swapflag | totalflag)) {
333 		(void)fprintf(stderr, usage);
334 		exit(1);
335 	}
336 	if (fileflag || totalflag)
337 		filemode();
338 	if (vnodeflag || totalflag)
339 		vnodemode();
340 	if (ttyflag)
341 		ttymode();
342 	if (swapflag || totalflag)
343 		swapmode();
344 	exit (0);
345 }
346 
347 struct e_vnode {
348 	struct vnode *avnode;
349 	struct vnode vnode;
350 };
351 
352 void
353 vnodemode()
354 {
355 	struct e_vnode *e_vnodebase, *endvnode, *evp;
356 	struct vnode *vp;
357 	struct mount *maddr, *mp;
358 	int numvnodes;
359 
360 	e_vnodebase = loadvnodes(&numvnodes);
361 	if (totalflag) {
362 		(void)printf("%7d vnodes\n", numvnodes);
363 		return;
364 	}
365 	endvnode = e_vnodebase + numvnodes;
366 	(void)printf("%d active vnodes\n", numvnodes);
367 
368 
369 #define ST	mp->mnt_stat
370 	maddr = NULL;
371 	for (evp = e_vnodebase; evp < endvnode; evp++) {
372 		vp = &evp->vnode;
373 		if (vp->v_mount != maddr) {
374 			/*
375 			 * New filesystem
376 			 */
377 			if ((mp = getmnt(vp->v_mount)) == NULL)
378 				continue;
379 			maddr = vp->v_mount;
380 			mount_print(mp);
381 			vnode_header();
382 			if (!strcmp(ST.f_fstypename, "ufs") ||
383 			    !strcmp(ST.f_fstypename, "mfs"))
384 				ufs_header();
385 			else if (!strcmp(ST.f_fstypename, "nfs"))
386 				nfs_header();
387 			else if (!strcmp(ST.f_fstypename, "union"))
388 				union_header();
389 			(void)printf("\n");
390 		}
391 		vnode_print(evp->avnode, vp);
392 		if (!strcmp(ST.f_fstypename, "ufs") ||
393 		    !strcmp(ST.f_fstypename, "mfs"))
394 			ufs_print(vp);
395 		else if (!strcmp(ST.f_fstypename, "nfs"))
396 			nfs_print(vp);
397 		else if (!strcmp(ST.f_fstypename, "union"))
398 			union_print(vp);
399 		(void)printf("\n");
400 	}
401 	free(e_vnodebase);
402 }
403 
404 void
405 vnode_header()
406 {
407 	(void)printf("ADDR     TYP VFLAG  USE HOLD");
408 }
409 
410 void
411 vnode_print(avnode, vp)
412 	struct vnode *avnode;
413 	struct vnode *vp;
414 {
415 	char *type, flags[16];
416 	char *fp = flags;
417 	int flag;
418 
419 	/*
420 	 * set type
421 	 */
422 	switch (vp->v_type) {
423 	case VNON:
424 		type = "non"; break;
425 	case VREG:
426 		type = "reg"; break;
427 	case VDIR:
428 		type = "dir"; break;
429 	case VBLK:
430 		type = "blk"; break;
431 	case VCHR:
432 		type = "chr"; break;
433 	case VLNK:
434 		type = "lnk"; break;
435 	case VSOCK:
436 		type = "soc"; break;
437 	case VFIFO:
438 		type = "fif"; break;
439 	case VBAD:
440 		type = "bad"; break;
441 	default:
442 		type = "unk"; break;
443 	}
444 	/*
445 	 * gather flags
446 	 */
447 	flag = vp->v_flag;
448 	if (flag & VROOT)
449 		*fp++ = 'R';
450 	if (flag & VTEXT)
451 		*fp++ = 'T';
452 	if (flag & VSYSTEM)
453 		*fp++ = 'S';
454 	if (flag & VXLOCK)
455 		*fp++ = 'L';
456 	if (flag & VXWANT)
457 		*fp++ = 'W';
458 	if (flag & VBWAIT)
459 		*fp++ = 'B';
460 	if (flag & VALIASED)
461 		*fp++ = 'A';
462 	if (flag == 0)
463 		*fp++ = '-';
464 	*fp = '\0';
465 	(void)printf("%8x %s %5s %4d %4d",
466 	    avnode, type, flags, vp->v_usecount, vp->v_holdcnt);
467 }
468 
469 void
470 ufs_header()
471 {
472 	(void)printf(" FILEID IFLAG RDEV|SZ");
473 }
474 
475 int
476 ufs_print(vp)
477 	struct vnode *vp;
478 {
479 	int flag;
480 	struct inode inode, *ip = &inode;
481 	char flagbuf[16], *flags = flagbuf;
482 	char *name;
483 	mode_t type;
484 
485 	KGETRET(VTOI(vp), &inode, sizeof(struct inode), "vnode's inode");
486 	flag = ip->i_flag;
487 #if 0	/* XXX */
488 	if (flag & IN_LOCKED)
489 		*flags++ = 'L';
490 	if (flag & IN_WANTED)
491 		*flags++ = 'W';
492 #endif
493 	if (flag & IN_RENAME)
494 		*flags++ = 'R';
495 	if (flag & IN_UPDATE)
496 		*flags++ = 'U';
497 	if (flag & IN_ACCESS)
498 		*flags++ = 'A';
499 	if (flag & IN_CHANGE)
500 		*flags++ = 'C';
501 	if (flag & IN_MODIFIED)
502 		*flags++ = 'M';
503 	if (flag & IN_SHLOCK)
504 		*flags++ = 'S';
505 	if (flag & IN_EXLOCK)
506 		*flags++ = 'E';
507 #if 0
508 	if (flag & IN_LWAIT)
509 		*flags++ = 'Z';
510 #endif
511 	if (flag == 0)
512 		*flags++ = '-';
513 	*flags = '\0';
514 
515 	(void)printf(" %6d %5s", ip->i_number, flagbuf);
516 	type = ip->i_mode & S_IFMT;
517 	if (S_ISCHR(ip->i_mode) || S_ISBLK(ip->i_mode))
518 		if (usenumflag || ((name = devname(ip->i_rdev, type)) == NULL))
519 			(void)printf("   %2d,%-2d",
520 			    major(ip->i_rdev), minor(ip->i_rdev));
521 		else
522 			(void)printf(" %7s", name);
523 	else
524 		(void)printf(" %7qd", ip->i_size);
525 	return (0);
526 }
527 
528 void
529 nfs_header()
530 {
531 	(void)printf(" FILEID NFLAG RDEV|SZ");
532 }
533 
534 int
535 nfs_print(vp)
536 	struct vnode *vp;
537 {
538 	struct nfsnode nfsnode, *np = &nfsnode;
539 	char flagbuf[16], *flags = flagbuf;
540 	int flag;
541 	char *name;
542 	mode_t type;
543 
544 	KGETRET(VTONFS(vp), &nfsnode, sizeof(nfsnode), "vnode's nfsnode");
545 	flag = np->n_flag;
546 	if (flag & NFLUSHWANT)
547 		*flags++ = 'W';
548 	if (flag & NFLUSHINPROG)
549 		*flags++ = 'P';
550 	if (flag & NMODIFIED)
551 		*flags++ = 'M';
552 	if (flag & NWRITEERR)
553 		*flags++ = 'E';
554 	if (flag & NQNFSNONCACHE)
555 		*flags++ = 'X';
556 	if (flag & NQNFSWRITE)
557 		*flags++ = 'O';
558 	if (flag & NQNFSEVICTED)
559 		*flags++ = 'G';
560 	if (flag == 0)
561 		*flags++ = '-';
562 	*flags = '\0';
563 
564 #define VT	np->n_vattr
565 	(void)printf(" %6d %5s", VT.va_fileid, flagbuf);
566 	type = VT.va_mode & S_IFMT;
567 	if (S_ISCHR(VT.va_mode) || S_ISBLK(VT.va_mode))
568 		if (usenumflag || ((name = devname(VT.va_rdev, type)) == NULL))
569 			(void)printf("   %2d,%-2d",
570 			    major(VT.va_rdev), minor(VT.va_rdev));
571 		else
572 			(void)printf(" %7s", name);
573 	else
574 		(void)printf(" %7qd", np->n_size);
575 	return (0);
576 }
577 
578 void
579 union_header()
580 {
581 	(void)printf("    UPPER    LOWER");
582 }
583 
584 int
585 union_print(vp)
586 	struct vnode *vp;
587 {
588 	struct union_node unode, *up = &unode;
589 
590 	KGETRET(VTOUNION(vp), &unode, sizeof(unode), "vnode's unode");
591 
592 	(void)printf(" %8x %8x", up->un_uppervp, up->un_lowervp);
593 	return (0);
594 }
595 
596 /*
597  * Given a pointer to a mount structure in kernel space,
598  * read it in and return a usable pointer to it.
599  */
600 struct mount *
601 getmnt(maddr)
602 	struct mount *maddr;
603 {
604 	static struct mtab {
605 		struct mtab *next;
606 		struct mount *maddr;
607 		struct mount mount;
608 	} *mhead = NULL;
609 	struct mtab *mt;
610 
611 	for (mt = mhead; mt != NULL; mt = mt->next)
612 		if (maddr == mt->maddr)
613 			return (&mt->mount);
614 	if ((mt = malloc(sizeof(struct mtab))) == NULL)
615 		err(1, NULL);
616 	KGETRET(maddr, &mt->mount, sizeof(struct mount), "mount table");
617 	mt->maddr = maddr;
618 	mt->next = mhead;
619 	mhead = mt;
620 	return (&mt->mount);
621 }
622 
623 void
624 mount_print(mp)
625 	struct mount *mp;
626 {
627 	int flags;
628 	const char *type;
629 
630 #define ST	mp->mnt_stat
631 	(void)printf("*** MOUNT %s %s on %s", ST.f_fstypename,
632 	    ST.f_mntfromname, ST.f_mntonname);
633 	if (flags = mp->mnt_flag) {
634 		int i;
635 		const char *sep = " (";
636 
637 		for (i = 0; mnt_flags[i].m_flag; i++) {
638 			if (flags & mnt_flags[i].m_flag) {
639 				(void)printf("%s%s", sep, mnt_flags[i].m_name);
640 				flags &= ~mnt_flags[i].m_flag;
641 				sep = ",";
642 			}
643 		}
644 		if (flags)
645 			(void)printf("%sunknown_flags:%x", sep, flags);
646 		(void)printf(")");
647 	}
648 	(void)printf("\n");
649 #undef ST
650 }
651 
652 struct e_vnode *
653 loadvnodes(avnodes)
654 	int *avnodes;
655 {
656 	int mib[2];
657 	size_t copysize;
658 	struct e_vnode *vnodebase;
659 
660 	if (memf != NULL) {
661 		/*
662 		 * do it by hand
663 		 */
664 		return (kinfo_vnodes(avnodes));
665 	}
666 	mib[0] = CTL_KERN;
667 	mib[1] = KERN_VNODE;
668 	if (sysctl(mib, 2, NULL, &copysize, NULL, 0) == -1)
669 		err(1, "sysctl: KERN_VNODE");
670 	if ((vnodebase = malloc(copysize)) == NULL)
671 		err(1, NULL);
672 	if (sysctl(mib, 2, vnodebase, &copysize, NULL, 0) == -1)
673 		err(1, "sysctl: KERN_VNODE");
674 	if (copysize % sizeof(struct e_vnode))
675 		errx(1, "vnode size mismatch");
676 	*avnodes = copysize / sizeof(struct e_vnode);
677 
678 	return (vnodebase);
679 }
680 
681 /*
682  * simulate what a running kernel does in in kinfo_vnode
683  */
684 struct e_vnode *
685 kinfo_vnodes(avnodes)
686 	int *avnodes;
687 {
688 	struct mntlist mountlist;
689 	struct mount *mp, mount;
690 	struct vnode *vp, vnode;
691 	char *vbuf, *evbuf, *bp;
692 	int num, numvnodes;
693 
694 #define VPTRSZ  sizeof(struct vnode *)
695 #define VNODESZ sizeof(struct vnode)
696 
697 	KGET(V_NUMV, numvnodes);
698 	if ((vbuf = malloc((numvnodes + 20) * (VPTRSZ + VNODESZ))) == NULL)
699 		err(1, NULL);
700 	bp = vbuf;
701 	evbuf = vbuf + (numvnodes + 20) * (VPTRSZ + VNODESZ);
702 	KGET(V_MOUNTLIST, mountlist);
703 	for (num = 0, mp = mountlist.cqh_first; ; mp = mp->mnt_list.cqe_next) {
704 		KGET2(mp, &mount, sizeof(mount), "mount entry");
705 		for (vp = mount.mnt_vnodelist.lh_first;
706 		    vp != NULL; vp = vp->v_mntvnodes.le_next) {
707 			KGET2(vp, &vnode, sizeof(vnode), "vnode");
708 			if ((bp + VPTRSZ + VNODESZ) > evbuf)
709 				/* XXX - should realloc */
710 				errx(1, "no more room for vnodes");
711 			memmove(bp, &vp, VPTRSZ);
712 			bp += VPTRSZ;
713 			memmove(bp, &vnode, VNODESZ);
714 			bp += VNODESZ;
715 			num++;
716 		}
717 		if (mp == mountlist.cqh_last)
718 			break;
719 	}
720 	*avnodes = num;
721 	return ((struct e_vnode *)vbuf);
722 }
723 
724 char hdr[]="  LINE RAW CAN OUT  HWT LWT     COL STATE  SESS      PGID DISC\n";
725 int ttyspace = 128;
726 
727 void
728 ttymode()
729 {
730 	struct tty *tty;
731 
732 	if ((tty = malloc(ttyspace * sizeof(*tty))) == NULL)
733 		err(1, NULL);
734 #if !defined(hp300) && !defined(mips)
735 	if (nl[SCONS].n_type != 0) {
736 		(void)printf("1 console\n");
737 		KGET(SCONS, *tty);
738 		(void)printf(hdr);
739 		ttyprt(&tty[0], 0);
740 	}
741 #endif
742 #ifdef vax
743 	if (nl[SNQD].n_type != 0)
744 		qdss();
745 	if (nl[SNDZ].n_type != 0)
746 		ttytype(tty, "dz", SDZ, SNDZ, 0);
747 	if (nl[SNDH].n_type != 0)
748 		ttytype(tty, "dh", SDH, SNDH, 0);
749 	if (nl[SNDMF].n_type != 0)
750 		ttytype(tty, "dmf", SDMF, SNDMF, 0);
751 	if (nl[SNDHU].n_type != 0)
752 		ttytype(tty, "dhu", SDHU, SNDHU, 0);
753 	if (nl[SNDMZ].n_type != 0)
754 		ttytype(tty, "dmz", SDMZ, SNDMZ, 0);
755 #endif
756 #ifdef tahoe
757 	if (nl[SNVX].n_type != 0)
758 		ttytype(tty, "vx", SVX, SNVX, 0);
759 	if (nl[SNMP].n_type != 0)
760 		ttytype(tty, "mp", SMP, SNMP, 0);
761 #endif
762 #ifdef hp300
763 	if (nl[SNITE].n_type != 0)
764 		ttytype(tty, "ite", SITE, SNITE, 0);
765 	if (nl[SNDCA].n_type != 0)
766 		ttytype(tty, "dca", SDCA, SNDCA, 0);
767 	if (nl[SNDCM].n_type != 0)
768 		ttytype(tty, "dcm", SDCM, SNDCM, 0);
769 	if (nl[SNDCL].n_type != 0)
770 		ttytype(tty, "dcl", SDCL, SNDCL, 0);
771 #endif
772 #ifdef mips
773 	if (nl[SNDC].n_type != 0)
774 		ttytype(tty, "dc", SDC, SNDC, 0);
775 #endif
776 #ifdef __FreeBSD__
777 	if (nl[NSCCONS].n_type != 0)
778 		ttytype(tty, "vty", SCCONS, NSCCONS, 0);
779 	if (nl[NSIO].n_type != 0)
780 		ttytype(tty, "sio", SIO, NSIO, 0);
781 	if (nl[NRC].n_type != 0)
782 		ttytype(tty, "rc", RC, NRC, 0);
783 	if (nl[NCY].n_type != 0)
784 		ttytype(tty, "cy", CY, NCY, 0);
785 	if (nl[NSI].n_type != 0)
786 		ttytype(tty, "si", SI, NSI, 1);
787 #endif
788 	if (nl[SNPTY].n_type != 0)
789 		ttytype(tty, "pty", SPTY, SNPTY, 0);
790 }
791 
792 void
793 ttytype(tty, name, type, number, indir)
794 	struct tty *tty;
795 	char *name;
796 	int type, number, indir;
797 {
798 	struct tty *tp;
799 	int ntty;
800 	struct tty **ttyaddr;
801 
802 	if (tty == NULL)
803 		return;
804 	KGET(number, ntty);
805 	(void)printf("%d %s %s\n", ntty, name, (ntty == 1) ? "line" : "lines");
806 	if (ntty > ttyspace) {
807 		ttyspace = ntty;
808 		if ((tty = realloc(tty, ttyspace * sizeof(*tty))) == 0)
809 			err(1, NULL);
810 	}
811 	if (indir) {
812 		KGET(type, ttyaddr);
813 		KGET2(ttyaddr, tty, ntty * sizeof(struct tty), "tty structs");
814 	} else {
815 		KGET1(type, tty, ntty * sizeof(struct tty), "tty structs");
816 	}
817 	(void)printf(hdr);
818 	for (tp = tty; tp < &tty[ntty]; tp++)
819 		ttyprt(tp, tp - tty);
820 }
821 
822 struct {
823 	int flag;
824 	char val;
825 } ttystates[] = {
826 #ifdef TS_WOPEN
827 	{ TS_WOPEN,	'W'},
828 #endif
829 	{ TS_ISOPEN,	'O'},
830 	{ TS_CARR_ON,	'C'},
831 #ifdef TS_CONNECTED
832 	{ TS_CONNECTED,	'c'},
833 #endif
834 	{ TS_TIMEOUT,	'T'},
835 	{ TS_FLUSH,	'F'},
836 	{ TS_BUSY,	'B'},
837 #ifdef TS_ASLEEP
838 	{ TS_ASLEEP,	'A'},
839 #endif
840 #ifdef TS_SO_OLOWAT
841 	{ TS_SO_OLOWAT,	'A'},
842 #endif
843 #ifdef TS_SO_OCOMPLETE
844 	{ TS_SO_OCOMPLETE, 'a'},
845 #endif
846 	{ TS_XCLUDE,	'X'},
847 	{ TS_TTSTOP,	'S'},
848 #ifdef TS_CAR_OFLOW
849 	{ TS_CAR_OFLOW,	'm'},
850 #endif
851 #ifdef TS_CTS_OFLOW
852 	{ TS_CTS_OFLOW,	'o'},
853 #endif
854 #ifdef TS_DSR_OFLOW
855 	{ TS_DSR_OFLOW,	'd'},
856 #endif
857 	{ TS_TBLOCK,	'K'},
858 	{ TS_ASYNC,	'Y'},
859 	{ TS_BKSL,	'D'},
860 	{ TS_ERASE,	'E'},
861 	{ TS_LNCH,	'L'},
862 	{ TS_TYPEN,	'P'},
863 	{ TS_CNTTB,	'N'},
864 #ifdef TS_CAN_BYPASS_L_RINT
865 	{ TS_CAN_BYPASS_L_RINT, 'l'},
866 #endif
867 #ifdef TS_SNOOP
868 	{ TS_SNOOP,     's'},
869 #endif
870 #ifdef TS_ZOMBIE
871 	{ TS_ZOMBIE,	'Z'},
872 #endif
873 	{ 0,	       '\0'},
874 };
875 
876 void
877 ttyprt(tp, line)
878 	struct tty *tp;
879 	int line;
880 {
881 	int i, j;
882 	pid_t pgid;
883 	char *name, state[20];
884 
885 	if (usenumflag || tp->t_dev == 0 ||
886 	   (name = devname(tp->t_dev, S_IFCHR)) == NULL)
887 		(void)printf("%7d ", line);
888 	else
889 		(void)printf("%7s ", name);
890 	(void)printf("%2d %3d ", tp->t_rawq.c_cc, tp->t_canq.c_cc);
891 	(void)printf("%3d %4d %3d %7d ", tp->t_outq.c_cc,
892 		tp->t_hiwat, tp->t_lowat, tp->t_column);
893 	for (i = j = 0; ttystates[i].flag; i++)
894 		if (tp->t_state&ttystates[i].flag)
895 			state[j++] = ttystates[i].val;
896 	if (j == 0)
897 		state[j++] = '-';
898 	state[j] = '\0';
899 	(void)printf("%-6s %8x", state, (u_long)tp->t_session);
900 	pgid = 0;
901 	if (tp->t_pgrp != NULL)
902 		KGET2(&tp->t_pgrp->pg_id, &pgid, sizeof(pid_t), "pgid");
903 	(void)printf("%6d ", pgid);
904 	switch (tp->t_line) {
905 	case TTYDISC:
906 		(void)printf("term\n");
907 		break;
908 	case NTTYDISC:
909 		(void)printf("ntty\n");
910 		break;
911 	case TABLDISC:
912 		(void)printf("tab\n");
913 		break;
914 	case SLIPDISC:
915 		(void)printf("slip\n");
916 		break;
917 	case PPPDISC:
918 		(void)printf("ppp\n");
919 		break;
920 	default:
921 		(void)printf("%d\n", tp->t_line);
922 		break;
923 	}
924 }
925 
926 void
927 filemode()
928 {
929 	struct file *fp;
930 	struct file *addr;
931 	char *buf, flagbuf[16], *fbp;
932 	int len, maxfile, nfile;
933 	static char *dtypes[] = { "???", "inode", "socket" };
934 
935 	KGET(FNL_MAXFILE, maxfile);
936 	if (totalflag) {
937 		KGET(FNL_NFILE, nfile);
938 		(void)printf("%3d/%3d files\n", nfile, maxfile);
939 		return;
940 	}
941 	if (getfiles(&buf, &len) == -1)
942 		return;
943 	/*
944 	 * Getfiles returns in malloc'd memory a pointer to the first file
945 	 * structure, and then an array of file structs (whose addresses are
946 	 * derivable from the previous entry).
947 	 */
948 	addr = ((struct filelist *)buf)->lh_first;
949 	fp = (struct file *)(buf + sizeof(struct filelist));
950 	nfile = (len - sizeof(struct filelist)) / sizeof(struct file);
951 
952 	(void)printf("%d/%d open files\n", nfile, maxfile);
953 	(void)printf("   LOC   TYPE    FLG     CNT  MSG    DATA    OFFSET\n");
954 	for (; (char *)fp < buf + len; addr = fp->f_list.le_next, fp++) {
955 		if ((unsigned)fp->f_type > DTYPE_SOCKET)
956 			continue;
957 		(void)printf("%x ", addr);
958 		(void)printf("%-8.8s", dtypes[fp->f_type]);
959 		fbp = flagbuf;
960 		if (fp->f_flag & FREAD)
961 			*fbp++ = 'R';
962 		if (fp->f_flag & FWRITE)
963 			*fbp++ = 'W';
964 		if (fp->f_flag & FAPPEND)
965 			*fbp++ = 'A';
966 #ifdef FSHLOCK	/* currently gone */
967 		if (fp->f_flag & FSHLOCK)
968 			*fbp++ = 'S';
969 		if (fp->f_flag & FEXLOCK)
970 			*fbp++ = 'X';
971 #endif
972 		if (fp->f_flag & FASYNC)
973 			*fbp++ = 'I';
974 		*fbp = '\0';
975 		(void)printf("%6s  %3d", flagbuf, fp->f_count);
976 		(void)printf("  %3d", fp->f_msgcount);
977 		(void)printf("  %8.1x", fp->f_data);
978 		if (fp->f_offset < 0)
979 			(void)printf("  %qx\n", fp->f_offset);
980 		else
981 			(void)printf("  %qd\n", fp->f_offset);
982 	}
983 	free(buf);
984 }
985 
986 int
987 getfiles(abuf, alen)
988 	char **abuf;
989 	int *alen;
990 {
991 	size_t len;
992 	int mib[2];
993 	char *buf;
994 
995 	/*
996 	 * XXX
997 	 * Add emulation of KINFO_FILE here.
998 	 */
999 	if (memf != NULL)
1000 		errx(1, "files on dead kernel, not implemented\n");
1001 
1002 	mib[0] = CTL_KERN;
1003 	mib[1] = KERN_FILE;
1004 	if (sysctl(mib, 2, NULL, &len, NULL, 0) == -1) {
1005 		warn("sysctl: KERN_FILE");
1006 		return (-1);
1007 	}
1008 	if ((buf = malloc(len)) == NULL)
1009 		err(1, NULL);
1010 	if (sysctl(mib, 2, buf, &len, NULL, 0) == -1) {
1011 		warn("sysctl: KERN_FILE");
1012 		return (-1);
1013 	}
1014 	*abuf = buf;
1015 	*alen = len;
1016 	return (0);
1017 }
1018 
1019 /*
1020  * swapmode is based on a program called swapinfo written
1021  * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
1022  */
1023 void
1024 swapmode()
1025 {
1026 	char *header, *p;
1027 	int hlen, nswap, nswdev, dmmax;
1028 	int i, div, avail, nfree, npfree, used;
1029 	struct swdevt *sw;
1030 	long blocksize, *perdev;
1031 	struct rlist head;
1032 	struct rlisthdr swaplist;
1033 	struct rlist *swapptr;
1034 	u_long ptr;
1035 
1036 	KGET(VM_NSWAP, nswap);
1037 	KGET(VM_NSWDEV, nswdev);
1038 	KGET(VM_DMMAX, dmmax);
1039 	KGET1(VM_SWAPLIST, &swaplist, sizeof swaplist, "swaplist");
1040 	if ((sw = malloc(nswdev * sizeof(*sw))) == NULL ||
1041 	    (perdev = malloc(nswdev * sizeof(*perdev))) == NULL)
1042 		err(1, "malloc");
1043 	KGET1(VM_SWDEVT, &ptr, sizeof ptr, "swdevt");
1044 	KGET2(ptr, sw, nswdev * sizeof(*sw), "*swdevt");
1045 
1046 	/* Count up swap space. */
1047 	nfree = 0;
1048 	memset(perdev, 0, nswdev * sizeof(*perdev));
1049 	swapptr = swaplist.rlh_list;
1050 	while (swapptr) {
1051 		int	top, bottom, next_block;
1052 
1053 		KGET2(swapptr, &head, sizeof(struct rlist), "swapptr");
1054 
1055 		top = head.rl_end;
1056 		bottom = head.rl_start;
1057 
1058 		nfree += top - bottom + 1;
1059 
1060 		/*
1061 		 * Swap space is split up among the configured disks.
1062 		 *
1063 		 * For interleaved swap devices, the first dmmax blocks
1064 		 * of swap space some from the first disk, the next dmmax
1065 		 * blocks from the next, and so on up to nswap blocks.
1066 		 *
1067 		 * The list of free space joins adjacent free blocks,
1068 		 * ignoring device boundries.  If we want to keep track
1069 		 * of this information per device, we'll just have to
1070 		 * extract it ourselves.
1071 		 */
1072 		while (top / dmmax != bottom / dmmax) {
1073 			next_block = ((bottom + dmmax) / dmmax);
1074 			perdev[(bottom / dmmax) % nswdev] +=
1075 				next_block * dmmax - bottom;
1076 			bottom = next_block * dmmax;
1077 		}
1078 		perdev[(bottom / dmmax) % nswdev] +=
1079 			top - bottom + 1;
1080 
1081 		swapptr = head.rl_next;
1082 	}
1083 
1084 	header = getbsize(&hlen, &blocksize);
1085 	if (!totalflag)
1086 		(void)printf("%-11s %*s %8s %8s %8s  %s\n",
1087 		    "Device", hlen, header,
1088 		    "Used", "Avail", "Capacity", "Type");
1089 	div = blocksize / 512;
1090 	avail = npfree = 0;
1091 	for (i = 0; i < nswdev; i++) {
1092 		int xsize, xfree;
1093 
1094 		/*
1095 		 * Don't report statistics for partitions which have not
1096 		 * yet been activated via swapon(8).
1097 		 */
1098 		if (!(sw[i].sw_flags & SW_FREED))
1099 			continue;
1100 
1101 		if (!totalflag)
1102 			if (sw[i].sw_dev != NODEV) {
1103 				p = devname(sw[i].sw_dev, S_IFBLK);
1104 				(void)printf("/dev/%-6s %*d ",
1105 					     p == NULL ? "??" : p,
1106 					     hlen, sw[i].sw_nblks / div);
1107 			} else
1108 				(void)printf("[NFS swap]  %*d ",
1109 					     hlen, sw[i].sw_nblks / div);
1110 
1111 		/* The first dmmax is never allocated to avoid trashing of
1112 		 * disklabels
1113 		 */
1114 		xsize = sw[i].sw_nblks - dmmax;
1115 		xfree = perdev[i];
1116 		used = xsize - xfree;
1117 		npfree++;
1118 		avail += xsize;
1119 		if (totalflag)
1120 			continue;
1121 		(void)printf("%8d %8d %5.0f%%    %s\n",
1122 		    used / div, xfree / div,
1123 		    (double)used / (double)xsize * 100.0,
1124 		    (sw[i].sw_flags & SW_SEQUENTIAL) ?
1125 			     "Sequential" : "Interleaved");
1126 	}
1127 
1128 	/*
1129 	 * If only one partition has been set up via swapon(8), we don't
1130 	 * need to bother with totals.
1131 	 */
1132 	used = avail - nfree;
1133 	free(sw);
1134 	free(perdev);
1135 	if (totalflag) {
1136 		(void)printf("%dM/%dM swap space\n", used / 2048, avail / 2048);
1137 		return;
1138 	}
1139 	if (npfree > 1) {
1140 		(void)printf("%-11s %*d %8d %8d %5.0f%%\n",
1141 		    "Total", hlen, avail / div, used / div, nfree / div,
1142 		    (double)used / (double)avail * 100.0);
1143 	}
1144 }
1145